8

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?

meetar
  • 7,443
  • 8
  • 42
  • 73
user1641165
  • 436
  • 2
  • 4
  • 17

1 Answers1

12

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){
    // ...
});
meetar
  • 7,443
  • 8
  • 42
  • 73
tmcw
  • 11,536
  • 3
  • 36
  • 45