There does not seem to be a command to get the number of layers in the map, or am I missing it?

One way to count the layers would be:


Or is there another preferred way? For instance, I would be interested in finding out how many vectors or how many basemaps have been added to the map, and I am not sure how to achieve that via the above snippet.


Leaflet's public API has an eachLayer method for the Map class:

let i = 0;
map.eachLayer(function(){ i += 1; });
console.log('Map has', i, 'layers.');

Please note that eachLayer will properly iterate through layers inside a L.LayerGroup, L.FeatureGroup and L.GeoJson.

Also note that .getLayers() works for LayerGroup (and FeatureGroup and GeoJson), but not for L.Map.

Usage of "private" properties and methods like _layers or _leaflet_id or _latlng is discouraged.


If you mean of features in a layer try:

console.log(myRoadLayer.getLayers().length + " Features in the Roads Layer");

If you mean basemaps like "Aerial", "Streets", "Topo" you define what you want in your map. Likewise overlay layers like "Roads", "Water", "Parcels" are also defined in the creation of your map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.