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?
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:
initialize the clusterer without markers:
var markerCluster = new MarkerClusterer(map);
set the function
markerCluster.setCalculator(calc);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With