Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weighted Marker Clusterer

Google Maps has a nice feature called Marker Clusterer which lets you to apply grid-based clustering to a collection of markers.

Marker Clusterer counts every marker as one, it sums up the number of markers in the grid. Differently, I want to assign a weight to every marker and sum up these weights in the cluster. Is it possible with Google Maps API? Do you know any other javascript library which provides a similar feature?

like image 788
metdos Avatar asked Mar 25 '14 09:03

metdos


1 Answers

It's not as complicated as it seems.

The markerclusterer-library provides the option to override the calculator-function(this is the function that will build the cluster-icons).

Store the weight as a property of the markers, e.g.:

new google.maps.Marker({position:new google.maps.LatLng(1,2),weight:8});

The calculator-function may look like this:

   var calc=function(markers, numStyles) {
      var weight=0;

      for(var i=0;i<markers.length;++i){
        weight+=markers[i].weight;
      }
        return {
        text: weight,
        index: Math.min(String(weight).length, numStyles)
      };
    }

To apply this custom function:

  1. initialize the clusterer without markers:

    var markerCluster = new MarkerClusterer(map); 
    
  2. set the function

    markerCluster.setCalculator(calc);
    
  3. add the markers:

    markerCluster.addMarkers(markers);
    

Demo: http://jsfiddle.net/doktormolle/H4EJu/

The pitfall: the calculator-function will have to iterate over all markers(by default it doesn't, it only calculates based on the length of the markers-array). This will affect the performance of the MarkerClusterer, especially when you have a lot of markers.

like image 194
Dr.Molle Avatar answered Oct 09 '22 13:10

Dr.Molle