Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting multiple markers in Layer Group

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/

like image 541
Alexandru Pufan Avatar asked Jan 03 '15 14:01

Alexandru Pufan


People also ask

How do I add a marker to a layer?

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.

How do you put a marker on a layer leaflet?

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.

What are layers in leaflet?

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.

How do you delete a layer on a map in leaflet?

map. removeLayer("EPSLayer"); map. removeLayer("tiles");


1 Answers

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/

like image 167
YaFred Avatar answered Oct 11 '22 12:10

YaFred