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 badges1 Answer
Reset to default 9You 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
版权声明:本文标题:javascript - Putting multiple markers in Layer Group - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741248492a2365343.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论