I have replicate and adjust this example from mapbox:
https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/
Everything is working fine but I want to have the geojson as an external file.
So I change this code:
var places = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'icon': 'theatre'
},
'geometry': {
'type': 'Point',
'coordinates': [-77.038659, 38.931567]
}
},
]
};
with this:
var places = '../images/destinations.geojson';
and I get this error in DevTools: Uncaught TypeError: Cannot read property 'forEach' of undefined.
The rest of the code (that I get the error) is this:
map.on('load', function() {
// Add a GeoJSON source containing place coordinates and information.
map.addSource('places', {
'type': 'geojson',
'data': places
});
places.features.forEach(function(feature) {
var symbol = feature.properties['icon'];
var layerID = 'poi-' + symbol;
// Add a layer for this symbol type if it hasn't been added already.
if (!map.getLayer(layerID)) {
map.addLayer({
'id': layerID,
'type': 'symbol',
'source': 'places',
'layout': {
'icon-image': symbol + '-15',
'icon-allow-overlap': true
},
'filter': ['==', 'icon', symbol]
});
One way to load an external geoJSON file would be to use d3js. See the example below, which is taken from this mapbox example. This example will draw a line for the coordinates given in the geoJSON file.
You should be able to iterate over data.features with your forEach loop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Load from an external geoJSON</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
mapboxgl.accessToken = '<access_token>';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-v9',
zoom: 0
});
map.on('load', function() {
// We use D3 to fetch the JSON here so that we can parse and use it separately
// from GL JS's use in the added source. You can use any request method (library
// or otherwise) that you want.
d3.json(
'https://docs.mapbox.com/mapbox-gl-js/assets/hike.geojson', //the geoJSON data file
function(err, data) {
if (err) throw err;
// save full coordinate list for later
var coordinates = data.features[0].geometry.coordinates;
// start by showing just the first coordinate
data.features[0].geometry.coordinates = [coordinates[0]];
// add it to the map
map.addSource('trace', { type: 'geojson', data: data });
map.addLayer({
'id': 'trace',
'type': 'line',
'source': 'trace',
'paint': {
'line-color': 'yellow',
'line-opacity': 0.75,
'line-width': 5
}
});
}
);
});
</script>
</body>
</html>
Related
I am trying to create cluster using ol 6.4.3. My script is
var cluster_data = {
"type": "Feature",
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [686213.47091037, 1093486.3776117],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687067.04391223, 1094462.7275206],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687214.60645801, 1094362.868384],
},
}
],
};
var features = new Array(3);
var source = new ol.layer.Vector({
features: new ol.format.GeoJSON().readFeatures(cluster_data),
});
var clusterSource = new ol.source.Cluster({
distance: 40,
source: source,
});
var styleCache = {};
var clusters = new ol.layer.Vector({
source: clusterSource,
style: function (feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new Style({
image: new CircleStyle({
radius: 10,
stroke: new Stroke({
color: '#fff',
}),
fill: new Fill({
color: '#3399CC',
}),
}),
text: new Text({
text: size.toString(),
fill: new Fill({
color: '#fff',
}),
}),
});
styleCache[size] = style;
}
return style;
},
});
map.addLayer(clusters);
I have added other 3 Tile layers map.getLayers().extend([bm,road,landmark]); and trying to add cluster over this. But getting error Uncaught TypeError: this.source.loadFeatures is not a function while adding cluster.
The map I got after adding my layer is
The error is because
var source = new ol.layer.Vector({
should be
var source = new ol.source.Vector({
Also the first type in the data before the features should be
"type": "FeatureCollection",
And if you are using the OpenLayers full build
new Style new CircleStyle new Stroke new Fill and new Text
should be
new ol.style.Style new ol.style.Circle new ol.style.Stroke new ol.style.Fill and new ol.style.Text
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://openlayers.org/en/v6.4.3/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v6.4.3/build/ol.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js"></script>
<style>
html, body, .map {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script>
proj4.defs("EPSG:32643","+proj=utm +zone=43 +datum=WGS84 +units=m +no_defs");
ol.proj.proj4.register(proj4);
var cluster_data = {
"type": "FeatureCollection",
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [686213.47091037, 1093486.3776117],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687067.04391223, 1094462.7275206],
},
},
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [687214.60645801, 1094362.868384],
},
}
],
};
var source = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(cluster_data),
});
var clusterSource = new ol.source.Cluster({
distance: 40,
source: source,
});
var styleCache = {};
var clusters = new ol.layer.Vector({
source: clusterSource,
style: function (feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: '#fff',
}),
fill: new ol.style.Fill({
color: '#3399CC',
}),
}),
text: new ol.style.Text({
text: size.toString(),
fill: new ol.style.Fill({
color: '#fff',
}),
}),
});
styleCache[size] = style;
}
return style;
},
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
projection: "EPSG:32643"
})
});
map.addLayer(clusters);
map.getView().fit(source.getExtent());
map.getView().setZoom(map.getView().getZoom() - 6);
</script>
</body>
</html>
I try to simplify my codebase for an ongoing project. I render different lines from different sources. Adding the source and layer one by one works as expected. But if I put this in an object it won't work. I even have no errors in the console. Now I am stuck at the following code
var trip_entries = {
t2: {
trip_id: 'trip-entry-2',
trip_geojson: '[[-0.15591514, 51.51830379],[-0.07571203, 51.51424049],[-0.08533793, 51.50438536],[-0.085793, 51.5036],[-0.084793, 51.503336],[-0.089793, 51.505336]]'
},
t3: {
trip_id: 'trip-entry-3',
trip_geojson: '[[-0.15514, 51.518],[-0.075703, 51.515],[-0.085793, 51.50],[-0.0793, 51.506],[-0.08473, 51.50336],[-0.0893, 51.536]]'
},
};
// Set route
$.each(trip_entries,function(key,value){
// Add sources
map.addSource(value.trip_id,{
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': value.trip_geojson
}
},
],
},
});
// Add layers
map.addLayer({
'id': value.trip_id,
'type': 'line',
'source': value.trip_id,
'layout': {
'line-join': 'round',
'line-cap': 'round'
},
'paint': {
'line-color': 'rgb(160,160,160)',
'line-width': 6,
}
});
});
You are passing the geoJSON as a string, rather than an array of coordinates. You should remove the ' ' on both of your geoJSONs to get the code to run. See below:
mapboxgl.accessToken =
"pk.eyJ1IjoicGxtYXBib3giLCJhIjoiY2s3MHkzZ3VnMDFlbDNmbzNiajN5dm9lOCJ9.nbbtDF54HIXo0mCiekVxng";
var map = new mapboxgl.Map({
container: "map", // container id
style: "mapbox://styles/mapbox/streets-v11", // stylesheet location
center: [-0.084793, 51.503336], // starting position [lng, lat]
zoom: 11 // starting zoom
});
var trip_entries = {
t2: {
trip_id: "trip-entry-2",
trip_geojson: [
[-0.15591514, 51.51830379],
[-0.07571203, 51.51424049],
[-0.08533793, 51.50438536],
[-0.085793, 51.5036],
[-0.084793, 51.503336],
[-0.089793, 51.505336]
]
},
t3: {
trip_id: "trip-entry-3",
trip_geojson: [
[-0.15514, 51.518],
[-0.075703, 51.515],
[-0.085793, 51.5],
[-0.0793, 51.506],
[-0.08473, 51.50336],
[-0.0893, 51.536]
]
}
};
map.on("load", function () {
// Set route
$.each(trip_entries, function (key, value) {
// Add sources
map.addSource(value.trip_id, {
type: "geojson",
data: {
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: {
type: "LineString",
coordinates: value.trip_geojson
}
}
]
}
});
// Add layers
map.addLayer({
id: value.trip_id,
type: "line",
source: value.trip_id,
layout: {
"line-join": "round",
"line-cap": "round"
},
paint: {
"line-color": "rgb(160,160,160)",
"line-width": 6
}
});
});
});
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.css" rel="stylesheet" />
<div id="map"></div>
I have a layer on mapbox studio containing all the postal code plotted on the map and I am accessing it using access key and layer id ,
I want to filter out only the postal code (marker) inside a radius
Turf provides a pointsWithinPolygon() function, that helps you to find any points within the circle. Here is an example:
mapboxgl.accessToken = 'pk.eyJ1IjoicGFybmRlcHUiLCJhIjoiY2l6dXZ5OXVkMDByZDMycXI2NGgyOGdyNiJ9.jyTchGQ8N1gjPdra98qRYg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v10',
center: [-46.6062, -23.5513],
zoom: 11
});
map.on('load', function () {
// List of your marker locations
var points = turf.points([
[-46.6318, -23.5523],
[-46.6246, -23.5325],
[-46.6062, -23.5513],
[-46.663, -23.554],
[-46.643, -23.557]
]);
// Create circle with radius
var center = [-46.6062, -23.5513];
var radius = 3;
var options = {steps: 10, units: 'kilometers', properties: {foo: 'bar'}};
var circle = turf.circle(center, radius, options);
// Find point within circle
var markerWithin = turf.pointsWithinPolygon(points, circle);
console.log("Found: " + markerWithin.features.length + " points");
// Draw circle polygon
map.addLayer({
'id': 'circle',
'type': 'fill',
'source': {
'type': 'geojson',
'data': circle
},
'layout': {},
'paint': {
'fill-color': '#525252',
'fill-opacity': 0.2
}
});
// Draw all points
map.addLayer({
'id': 'points',
'type': 'circle',
'source': {
'type': 'geojson',
'data': points
},
'layout': {},
'paint': {
'circle-radius': 5,
'circle-color': 'red',
'circle-opacity': 1
}
});
// Draw marker with in circle
markerWithin.features.forEach(function(marker) {
// Create marker
new mapboxgl.Marker()
.setLngLat(marker.geometry.coordinates)
.addTo(map);
});
});
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; };
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css' rel='stylesheet' />
<script src='https://npmcdn.com/#turf/turf/turf.min.js'></script>
<div id='map'></div>
does some Leaflet guru has an idea, what's the easiest way to make a CircleMarker draggable in Leaflet v1.0.3?
It's easy to do it for "standard" markers by using the "draggable"-option. But such an option doesn't exist for CircleMarker. I tried it by using several Events, but the problem is, that not the marker is being moved but the underlying map.
Another possibility could be the use of "stopPropagation"-Function (but just for DOMEvents). Or the use of "removeEventParent"... if the "parent" of the CircleMarker is the map and its events?
Regarding to the Documentation there also DOMUtility/Draggable-class. Is this what I need?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draggable Markers</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.0.3/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.0.3/dist/leaflet.js"></script>
<style>
body {padding: 0; margin: 0;}
html, body, #map {height: 100%;}
</style>
</head>
<body>
<div id="map"></div>
<script>
var layerOsm = new L.TileLayer('https://{s}.api.mapbox.com/v4/mapbox.outdoors/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoicHBldGUiLCJhIjoiY2lsdmE2ZmQ2MDA4OHZxbTZpcmx1emtqbSJ9.Two7SPSaIZysqgOTrrLkRg', {
subdomains: 'ab', maxZoom: 20, noWrap:true, attribution:'Mapbox | OpenStreetMap' });
var map = new L.Map('map').addLayer(layerOsm).setView(new L.LatLng(47.8, 13.0), 14);
L.marker([47.8, 13.0], {draggable:true}).addTo(map);
var circle = L.circleMarker([47.81, 13.01], {radius:30}).addTo(map);
circle.on('mousedown', function () {
map.on('mousemove', function (e) {
circle.setLatLng(e.latlng);
});
});
map.on('mouseup', function(){
map.removeEventListener('mousemove');
})
</script>
</body>
</html>
Leaflet v1.0+ solution:
var marker = L.circleMarker([41.91847, -74.62634]).addTo(map)
// extract trackCursor as a function so this specific
// "mousemove" listener can be removed on "mouseup" versus
// all listeners if we were to use map.off("mousemove")
function trackCursor(evt) {
marker.setLatLng(evt.latlng)
}
marker.on("mousedown", function() {
map.dragging.disable()
map.on("mousemove", trackCursor)
})
map.on("mouseup", function() {
map.dragging.enable()
map.off("mousemove", trackCursor)
})
To make this behaviour more re-useable we could encapsulate it in a function (JS ES6 syntax):
function moveableMarker(map, marker) {
function trackCursor(evt) {
marker.setLatLng(evt.latlng)
}
marker.on("mousedown", () => {
map.dragging.disable()
map.on("mousemove", trackCursor)
})
marker.on("mouseup", () => {
map.dragging.enable()
map.off("mousemove", trackCursor)
})
return marker
}
You can then make a marker draggable / moveable like so:
const moveable = moveableMarker(map, marker)
These examples helped construct the above solution:
Akshay Agrawal's JS Fiddle example
Jedidiah Hurt's Leaflet 1.0 draggable circle
Found another answer at https://github.com/w8r/Leaflet.Path.Drag/
I just added the Leaflet.Path.Drag.js. Now I can read in from my REST service all my sites and move them.
var data = {
"type": "FeatureCollection",
"features": [
{
"geometry": {
"type": "Point",
"coordinates": [
-73.7979125, 42.704642
]
},
"type": "Feature",
"properties": {
"popupContent": "This is Point 1. "
},
"id": 51
},
{
"geometry": {
"type": "Point",
"coordinates": [
-73.630371,42.698585
]
},
"type": "Feature",
"properties": {
"popupContent": "This is Point 2. "
},
"id": 52
}
]
};
var map = L.map('map', {editable: true}).setView([43, -74], 8);
var osm=new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',{
attribution: '© OpenStreetMap //contributors'}).addTo(map);
function onEachFeature(feature, layer) {
var popupContent = feature.properties.popupContent
layer.bindPopup(popupContent);
layer.on('dragend', function(e){
console.log(layer.getLatLng().lat);
console.log(layer.getLatLng().lng);
});
}
var mymarker =L.geoJSON(data, {
style: function (feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: onEachFeature,
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng,{ draggable: true }, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
});
}
}).addTo(map);
Working with leaflet api where i have added a custom marker control...
There also we can add multiple baseLayer and toggle between these layers....
Lately i was trying to bind the markers with this base layer and i can't understand the documentaion very well so having difficulty if someone help.....
Script
//Custom control for marker
L.easyButton('fa-arrow', function () {
map.on('click', function arrow(e) {
L.marker(e.latlng, { icon: arrIcon, draggable: true}).addTo(map);
map.off('click', arrow);
});
}).addTo(map);
//already added layer and needs to bind marker with this
var layerGroup = new L.LayerGroup(),
imageOverlayUrl = 'abc.jpg',
imageOverlay = new L.ImageOverlay(imageOverlayUrl, bounds).addTo(layerGroup),
featureGroup = new L.FeatureGroup().addTo(layerGroup);
var layerGroupings = { "Main": layerGroup };
var layerControl = new L.control.layers(layerGroupings,null, { collapsed: false }).addTo(map);
In short, i have a need to bind my custom marker with this layer i have defined in script, if there is a way please guide or give reference..thanks for your time
I am not sure if this is what you are looking for.
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/leaflet/dist/leaflet.js"></script>
<script src="../dist/angular-leaflet-directive_dev_mapped.js"></script>
<link rel="stylesheet" href="../bower_components/leaflet/dist/leaflet.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
var app = angular.module("demoapp", ["leaflet-directive"]);
app.controller('MixedMOverlaysMarkersNestedNoWatchController', function ($scope, leafletData, $timeout) {
var _clonedMarkers;
$timeout(function () {
//should do nothing (not watched) and only see one destroy
_clonedMarkers = angular.extend({},$scope.markers);
$scope.markers = {};
},1000);
$timeout(function () {
leafletData.getDirectiveControls().then(function (controls) {
//move all markers by a few decimal points
for (var layer in _clonedMarkers) {
var markerSet = _clonedMarkers[layer];
for (var markerName in markerSet) {
var marker = markerSet[markerName];
marker.lat += .05;
}
}
//force manual update
$scope.markers = _clonedMarkers;
controls.markers.create($scope.markers);
});
}, 4000);
angular.extend($scope, {
markersWatchOptions: {
doWatch: false,
isDeep: false,
individual: {
doWatch: false,
isDeep: false
}
},
center: {
lat: 42.20133,
lng: 2.19110,
zoom: 11
},
layers: {
baselayers: {
osm: {
name: 'OpenStreetMap',
type: 'xyz',
url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
layerOptions: {
subdomains: ['a', 'b', 'c'],
attribution: '© OpenStreetMap contributors',
continuousWorld: true
}
},
cycle: {
name: 'OpenCycleMap',
type: 'xyz',
url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
layerOptions: {
subdomains: ['a', 'b', 'c'],
attribution: '© OpenCycleMap contributors - © OpenStreetMap contributors',
continuousWorld: true
}
}
},
overlays: {
hillshade: {
name: 'Hillshade Europa',
type: 'wms',
url: 'http://129.206.228.72/cached/hillshade',
visible: true,
layerOptions: {
layers: 'europe_wms:hs_srtm_europa',
format: 'image/png',
opacity: 0.25,
attribution: 'Hillshade layer by GIScience http://www.osm-wms.de',
crs: L.CRS.EPSG900913
}
},
fire: {
name: 'OpenFireMap',
type: 'xyz',
url: 'http://openfiremap.org/hytiles/{z}/{x}/{y}.png',
layerOptions: {
attribution: '© OpenFireMap contributors - © OpenStreetMap contributors',
continuousWorld: true
}
},
cars: {
name: 'Cars',
type: 'group',
visible: true
},
bikes: {
name: 'Bicycles',
type: 'group',
visible: false
},
runners: {
name: 'Runners',
type: 'group',
visible: false
}
}
},
markers: {
cars: {
m1: {
lat: 42.20133,
lng: 2.19110,
message: "I'm a car"
},
m2: {
lat: 42.21133,
lng: 2.18110,
message: "I'm a car"
}
},
bikes: {
m3: {
lat: 42.19133,
lng: 2.18110,
layer: 'bikes',
message: 'A bike!!'
},
m4: {
lat: 42.3,
lng: 2.16110,
layer: 'bikes'
}
},
runners: {
m5: {
lat: 42.1,
lng: 2.16910
},
m6: {
lat: 42.15,
lng: 2.17110
}
}
}
});
});
</script>
</head>
<body ng-controller="MixedMOverlaysMarkersNestedNoWatchController">
<leaflet
center="center"
markers="markers"
layers="layers"
markers-nested="true"
markers-watch-options="markersWatchOptions"
height="480px" width="100%">
</leaflet>
<h1>Overlays with nested markers no watchers example</h1>
</body>
</html>
*Source: https://tombatossals.github.io/angular-leaflet-directive/examples/0000-viewer.html#/mixed/overlays-markers-nested-no-watch-example