Search code examples
javascriptcountleafletnanmarkers

Counting markers in a layer in leaflet and add it to a div


I have a Leaflet map with markers and filters (checkboxes) and I would like to count the number of markers as the filters change.

I added this code which I found here Getting the count of markers in a layer in leaflet :

var counter = 0;

function onEachFeature(feature, layer) {
counter++;
console.log(counter)
}

L.geoJson(geojsonFeature, {
onEachFeature: onEachFeature
}).addTo(map);

The code works well but returns a NaN property. I would like to know if there is a way to reach the counter result as I would like to insert it in a div to my Leaflet Map? Expected result

Thanks a lot!


Solution

  • The first question is, do you have a geojson feature / geojson group or only markers?

    If you have a GeoJSON group:

    The simplest way would be to get all child layers of the geojson group, which is the marker count:

    var group = L.geoJson(geojsonFeature, {
       onEachFeature: onEachFeature
    }).addTo(map);
    
    var counter = group.getLayers().length;
    

    If you have only markers on the map (not in a group):

    You can loop through all layers of the map and check if the layer is existing on the map:

    var counter = 0;
    map.eachLayer((layer)=>{
       if(layer instanceof L.Marker){
         counter++;
       }
    });
    

    Displaying the data as Control

    L.MarkerCounterControl = L.Control.extend({
        options: {
            position: 'topright'
            //control position - allowed: 'topleft', 'topright', 'bottomleft', 'bottomright'
        },
    
        onAdd: function (map) {
            var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control fitall');
            this.button = L.DomUtil.create('a', '', container);
                    this.button.style.width = 'auto';
                    this.button.style.padding = '2px 5px';
            this.button.innerHTML = '0 Markers';
            L.DomEvent.disableClickPropagation(this.button);
    
            return container;
        },
            setCount(count) {
                this.button.innerHTML = count+' Markers';
            }
    });
    
    var control = new L.MarkerCounterControl().addTo(map)
    control.setCount(10)
    

    You can call after each layer change control.setCount(counter)

    Demo: https://plnkr.co/edit/dyQKVQFDm5sBHzUK