6
votes

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?

1
You can modify Marker Clusterer library for that. - Anto Jurković
assinging the weight to every marker and summing them up should be easy, as each marker should be a lat lng pair you have stored on a database or something, so you just set the weight value along the coordinates, and as to fetch all those markers you will need a loop, you can just fetch the weight as well and sum them up in a temporal variable. The problem will be mainly to display that weight. - aleation

1 Answers

7
votes

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.