illwalkwithyou
illwalkwithyou

Reputation: 359

Leaflet Marker Cluster add weight to marker

I have a leaflet map and I am using the Leaflet.markerCluster plugin to cluster my markers. I have some markers that represent multiple points on the same location. Unfortunately when it gets clustered it only represents one single point. Is there a way to add a weight to each marker? So that the cluster sees it as more than one point?

Basically I am hoping for a clusterWeight property like the follwing:

var newMarker = L.marker(coordinates, {
            icon: myIcon,
            clusterWeight: 5
        });

This propety does not exist however. Anyoneknow of a work around? Thanks!

Upvotes: 1

Views: 1481

Answers (1)

chrki
chrki

Reputation: 6323

First you will need to create a marker that supports custom properties. You can do this by extending the default L.Marker like so:

var weightMarker = L.Marker.extend({
   options: { 
      customWeight: 0
   }
});

Then you can make use of Leaflet.markercluster's iconCreateFunction to create a custom cluster marker, by changing what is displayed on the marker:

var markers = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        // iterate all markers and count
        var markers = cluster.getAllChildMarkers();
        var weight = 0;
        for (var i = 0; i < markers.length; i++) {
            if(markers[i].options.hasOwnProperty("customWeight")){
            weight += markers[i].options.customWeight;                
          }
        }

        var c = ' marker-cluster-';
        if (weight < 10) {
            c += 'small';
        } else if (weight < 100) {
            c += 'medium';
        } else {
            c += 'large';
        }
        // create the icon with the "weight" count, instead of marker count
        return L.divIcon({ 
            html: '<div><span>' + weight + '</span></div>',
            className: 'marker-cluster' + c, iconSize: new L.Point(40, 40)
        });
    }
});

Demo: https://jsfiddle.net/chk1/0hq1t13t/

Upvotes: 4

Related Questions