Leaflet clustermarker with custom icon

10,530

Using the example here: https://github.com/Leaflet/Leaflet.markercluster/blob/master/example/marker-clustering-custom.html

And the documentation of L.divIcon is here: http://leafletjs.com/reference.html#divicon

I came up with this example: http://franceimage.github.io/leaflet/8/?map=46.566414,2.4609375,6

Hopefully it will help you

Meaningful parts are:

var markerCluster = new L.MarkerClusterGroup({ 
    iconCreateFunction: function (cluster) {
        var markers = cluster.getAllChildMarkers();
        var html = '<div class="circle">' + markers.length + '</div>';
        return L.divIcon({ html: html, className: 'mycluster', iconSize: L.point(32, 32) });
    },
    spiderfyOnMaxZoom: false, showCoverageOnHover: true, zoomToBoundsOnClick: false 
});

and css

.circle {
    width: 32px;
    height: 32px;
    line-height: 32px;
    background-image: url('circle.png');
    text-align: center;
}

There may be other ways ...

Share:
10,530
Sandra
Author by

Sandra

"meep."

Updated on June 28, 2022

Comments

  • Sandra
    Sandra almost 2 years

    I've managed to cluster my markers. What I want to do now is to display a custom icon with the number of points in the cluster, but I can't figure out how to do that or if it's even possible.

    I read the documentation and understood that I need to implement my own iconCreateFunction when creating the marker cluster.

    addSomeMarkers: function(data, markerProperties) {
       var markers = L.markerClusterGroup({
          iconCreateFunction: function(cluster) {
             // TODO
          }
       });
       ....
    }
    

    I know I can return L.divIcon with a custom css class and cluster.getChildCount(), but I can't specify markerProperties.iconUrl as an image that should be displayed. I could also use L.icon with my custom icon from markerProperties.iconUrl, but in that case I don't see how I should get cluster.getChildCount() to display.

    So what I need is a combination of both. Is there anything like that? And if not, can someone hint a workaround to achieve this?

  • Sandra
    Sandra almost 10 years
    Shame on me that I didn't think of this. Thank you!
  • SKuijers
    SKuijers over 3 years
    Not Directly related to the original question but worth to note that instead of markers.length you can call cluster.getChildCount().