javascript 循环遍历传单地图图层
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21748875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through Leaflet Map layers
提问by user1641165
I'm using Leaflet JS to build my maps, but I'm having a few issues selecting layers.
我正在使用 Leaflet JS 来构建我的地图,但是我在选择图层时遇到了一些问题。
I'm aiming to fit my map to a polygon. Leaflet generates a Leaflet ID for each element on the map, but these IDs are random. So I want to create an array which links each Leaflet ID with a known polygon ID.
我的目标是让我的地图适合多边形。Leaflet 为地图上的每个元素生成一个 Leaflet ID,但这些 ID 是随机的。所以我想创建一个数组,将每个传单 ID 与一个已知的多边形 ID 链接起来。
The concept comes from here How to interact with leaflet marker layer from outside the map?but I'm unsure how to implement it.
这个概念来自这里如何从地图外与传单标记层交互?但我不确定如何实现它。
The object 'map._layers' stores all the elements including the ID of each polygon. So I'm looping through it as follows:
对象“map._layers”存储所有元素,包括每个多边形的 ID。所以我循环遍历它如下:
var idstore = [];
for (var x in map._layers) {
// here idstore[x['polyid']] = x;
}
Now I can use that array to associate my polygon IDs to Leaflet IDs. The resulting array should be as follows:
现在我可以使用该数组将我的多边形 ID 与传单 ID 相关联。结果数组应如下所示:
array('polygonid'=>'leafletid','155447'=>'478','748745' => 479);
My problem is the loop isn't working correctly. I can only see the first 2 records coming up which are actually overlays (map tiles). The elements are definitely in that object though.
我的问题是循环工作不正常。我只能看到前 2 条记录实际上是叠加层(地图图块)。元素肯定在那个对象中。
What am I doing wrong?
我究竟做错了什么?
回答by tmcw
A good first step would be looking through the Leaflet reference documentationand using the documented .eachLayer
function instead of a for loop on a private variable.
一个好的第一步是查看Leaflet 参考文档并使用记录的.eachLayer
函数而不是私有变量上的 for 循环。
var idstore = [];
map.eachLayer(function(layer){
// ...
});