Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through Leaflet Map layers

I'm using Leaflet JS to build my maps, but I'm having a few issues selecting layers.

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.

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:

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:

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.

What am I doing wrong?

like image 509
user1641165 Avatar asked Feb 13 '14 08:02

user1641165


1 Answers

A good first step would be looking through the Leaflet reference documentation and using the documented .eachLayer function instead of a for loop on a private variable.

var idstore = [];
map.eachLayer(function(layer){
    // ...
});
like image 188
tmcw Avatar answered Oct 22 '22 11:10

tmcw