admin管理员组

文章数量:1277901

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/{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: /

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/{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/pufanalexandru/gryvsae2/

Share Improve this question edited Jan 5, 2022 at 13:24 TidyDev 3,6689 gold badges34 silver badges55 bronze badges asked Jan 3, 2015 at 14:47 Alexandru PufanAlexandru Pufan 1,9123 gold badges29 silver badges45 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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./reference.html#layergroup

See your corrected code here: http://jsfiddle/FranceImage/oLfnc5u3/

本文标签: javascriptPutting multiple markers in Layer GroupStack Overflow