Jafo
Jafo

Reputation: 1331

Is there any way to count how many visible markers or marker clusters are in the Leaflet map view?

Is there are way to count how many markers (or clusters) are currently visible on the current map view (without scrolling)?

Upvotes: 1

Views: 1060

Answers (1)

peeebeee
peeebeee

Reputation: 2618

Simplistically you can iterate all the layers on the map, and for those that are a marker, count how many are within the map bounds.

function countVisibleMarkers(map) {
    var bounds = map.getBounds();
    var count = 0;

    map.eachLayer(function(layer) {
        if (layer instanceof L.Marker) {
            if (bounds.contains(layer.getLatLng())) count++;
         }
    });
    return count;
}

Upvotes: 3

Related Questions