Loop through Leaflet Map layers

23,693

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){
    // ...
});
Share:
23,693
user1641165
Author by

user1641165

Updated on March 12, 2020

Comments

  • user1641165
    user1641165 about 4 years

    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?