I am trying to create multiple markers with a for loop, storing coordinates into an array. Then, I would like to put that markers into a layer group, and be able to show/hide them using L.control.layers. The problem is that only the last marker created will be shown. I know that this is something related to closures and scope, but I'm new to JavaScript and I don't yet understand this things.
var map = L.map('map').setView([44.6499282, 22.6327532], 14);
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var coordinates = [
[44.649, 22.632],
[44.650, 22.642],
[44.652, 22.632]
];
for (i = 0; i < coordinates.length; i++) {
marker = L.marker([coordinates[i][0], coordinates[i][1]]);
marker.addTo(map);
}
var overlay = {'markers': marker};
L.control.layers(null, overlay).addTo(map);
Here's a link to JSFiddle: http://jsfiddle.net/pufanalexandru/gryvsae2/
Click Add new layer at the bottom of the Map chart list. A list of the layer options is displayed. From the list, click Marker layer. The marker layer is added to the Map chart layer list, the Properties list for the layer is displayed, and the layer with its default settings is added to the map chart.
Adding a Simple MarkerStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
In Leaflet, a “layer” is anything that moves around when the map is moved around. Before seeing how to create them from scratch, it's easier to explain how to do simple extensions.
map. removeLayer("EPSLayer"); map. removeLayer("tiles");
You have to create a layerGroup that will contain your markers. You add the layerGroup to the map (not the markers)
var layerGroup = L.layerGroup().addTo(map);
for (i = 0; i < coordinates.length; i++) {
marker = L.marker([coordinates[i][0], coordinates[i][1]]);
layerGroup.addLayer(marker);
}
var overlay = {'markers': layerGroup};
L.control.layers(null, overlay).addTo(map);
See doc here: http://leafletjs.com/reference.html#layergroup
See your corrected code here: http://jsfiddle.net/FranceImage/oLfnc5u3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With