Is there a straightforward way to get the number of layers in a Leaflet LayerGroup? A quick glance at the documentation says there isn't at the moment.
Image OverlayStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class. Step 4 − Create the image overlay using L.
Use the addLegend function to add a legend. The easiest way to use addLegend is to provide pal (a palette function, as generated from colorNumeric et al.) and values , and let it calculate the colors and labels for you.
Used to load and display tile layers on the map, implements ILayer interface.
Since my first answer, the LayerGroup
has been extended with a getLayers()
method, making the solution straightforward:
layerGroup.getLayers().length
.
Looking at the LayerGroup code, you should be able to get the number of layers by layerGroup._layers.length
.
But note that _layers
by the implementors is intended to be private, so I guess you cannot be sure this will work in future versions.
If you want to stay within the public API, then you could call eachLayer
and count the layers.
As Asborn hinted at you can access the maps layer object through any layer event object.
e.g.
map.addEventListener('viewreset', function(event){
console.log(event.target._layers);
}, false);
to get the length you would need to count the keys and the easiest way is you use ECMA (chrome, node etc)
Object.keys(map._layers).length
I'm surprised there isnt a API to get this info such as
maps.getLayers();
:)
EDIT: actually there is: http://leafletjs.com/reference.html#layergroup
getLayers()
and it returns an array of the layers within that group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With