Easy way to get size of Leaflet LayerGroup?

2019-05-04 00:37发布

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.

3条回答
放我归山
2楼-- · 2019-05-04 00:42

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

查看更多
不美不萌又怎样
3楼-- · 2019-05-04 01:01

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.

查看更多
乱世女痞
4楼-- · 2019-05-04 01:05

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.

查看更多
登录 后发表回答