Search code examples
javascriptcountleafleticonslegend

Is it possible to count the occurrence number of a custom icon in Leaflet? If yes, how to do it?


Firstly, I'm a beginner, I've learned a lot from you. I have 5 custom icons defined:

//Awesome icons
var LeafIcon = L.Icon.extend({
    options: {
        shadowUrl: "markers-shadow.png",
        iconSize:     [35, 45],
        shadowSize:   [36, 16],
        iconAnchor:   [17, 42],
        shadowAnchor: [10, 12],
        popupAnchor:  [1, -32]
    }
});

var blueIcon = new LeafIcon({iconUrl: 'blue.png'});
var greenIcon = new LeafIcon({iconUrl: 'green.png'});
var yellowIcon = new LeafIcon({iconUrl: 'yellow.png'});
var orangeIcon = new LeafIcon({iconUrl: 'orange.png'});
var redIcon = new LeafIcon({iconUrl: 'red.png'});

The icons represent the construction conditions. Would it be possible to count the number of occurrences for each icon as the overlayMaps are selected? With the result, you need to make a legend with the result and rename the icons to appear, for example: Blue 5 occurrences, Green 2 occurrences, Yellow 12 occurrences, Orange 0 occurrences and Red 21 occurrences. I appreciate the help.


Solution

  • You can iterate over your markers on the map (or on other layer such as a feature group) and count how many time which icon was used:

    function countMarkers(featureGroup) {
        const count = {};
        for (const layer of featureGroup.getLayers()) {
            const icon = layer.getIcon();
            const url = icon.options.iconUrl;
            count[url] = (count[url] || 0) + 1;
        }
        return count;
    }
    
    // featureGroup is an instance of L.featureGroup
    const result = countMarkers(featureGroup);
    
    // example return: { "blue.png": 3, "orange.png": 1 }
    console.log(result);
    

    The example assumes that you have your markers added to a L.featureGroup instance (featureGroup) and that your icon URL can be used as an ID.