Easy way to get size of Leaflet LayerGroup?

2019-05-04 00:50发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

There is an easy way to get all functions related to leaflet or another by just typing the variable name or function name or leaflet layer name.

 here I used google chrome console manager.
 just type the layer name you will get all the functions related to it

pls look at the below pic : https://i.stack.imgur.com/1LDz0.png