Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to get size of Leaflet LayerGroup?

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.

like image 554
Matt Hampel Avatar asked Aug 30 '12 01:08

Matt Hampel


People also ask

How do you add an overlay to a leaflet?

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.

How do you add a legend to a leaflet map?

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.

What is tile layer in leaflet?

Used to load and display tile layers on the map, implements ILayer interface.


2 Answers

Updated Answer

Since my first answer, the LayerGroup has been extended with a getLayers() method, making the solution straightforward:

layerGroup.getLayers().length.


**OLD** REDUNDANT ANSWER:

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.

like image 152
Asbjørn Avatar answered Sep 27 '22 18:09

Asbjørn


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.

like image 34
sidonaldson Avatar answered Sep 27 '22 19:09

sidonaldson