Leaflet – Count Features by Type in a FeatureGroup Using JavaScript

javascriptleaflet

Is there any way in leaflet to get the number of rectangles in a feature group?
I know this code that work: drawnItems.getLayers().length; but it counts all the objects within the drawnItems featuregroup. I only need the a specific type of features, for example rectangle

Best Answer

Assuming that you are using instances of L.Rectangle, you can use functional programming like so:

drawnItems.getLayers().filter( function(l) {return l instanceof L.Rectangle} ).length;

The filter method of Array will return another array, containing only the elements which make the callback function return true; in this case, it will return an array containing only those layers which are instances of L.Rectangle.

Related Question