11

I am wondering if it is possible for clusterMarkers in leaflet to display frequency information instead of the number of markers clustered?

I have the following code

getColor <- function(my.df) {
  sapply(my.df$value, function(value) {
  if(value <= 5) {
    "green"
  } else if(value <= 25) {
    "orange"
  } else {
    "red"
  } })
}
icons <- awesomeIcons(
  icon = 'ios-close',
  iconColor = 'black',
  library = 'ion',
  markerColor = getColor(my.df)
)


map <- my.df %>% 
    leaflet () %>%
    addTiles() %>%
    addAwesomeMarkers(icon=icons, label=~as.character(freq), clusterOptions = markerClusterOptions())
map

my.df is in the following format

longitude latitude freq
XX.xxx    XX.xxx    3
XX.xxx    XX.xxx    7
XX.xxx    XX.xxx    4
.
.
.
XX.xxx    XX.xxx    6

What I would like is for the cluster to display the aggregate of the value for my.df$freq rather than the number of pins in the cluster. I am not sure how to do this though or if there is even a clusterOption for this.

JWH2006
  • 239
  • 1
  • 11
  • please report `dput(my.df)`. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Iman Aug 05 '18 at 15:19

1 Answers1

3

Yes, this is possible.

You have to make use of iconCreateFunction function which is inserted as an option to MarkerClusterGroup for creating custom cluster icons. You also need to make use of getAllChildMarkers() function to iterate through all children of a cluster and calculate aggregate value.

var markers = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        let children = cluster.getAllChildMarkers();

        let sum = 0;
        for (let i = 0; i < children.length; i++) {
            sum += children[i].options.value;
        }

        return new L.DivIcon({ html: '<b>' + sum + '</b>' });
    }
}).addTo(map);

L.circleMarker([0,0], {value: 10}).addTo(markers);
L.circleMarker([10,0], {value: 20}).addTo(markers);
L.circleMarker([40,10], {value: 60}).addTo(markers);

Of course, you can customize the icon.

This jsfiddle: https://jsfiddle.net/41mknp5s/1/ is an implementation of the above code. Zoom in/out to see the cluster showing the sum values of the markers.

treecon
  • 2,415
  • 2
  • 14
  • 28