Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clustermarkers in leaflet providing density information in R

Tags:

r

gis

leaflet

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.

like image 987
JWH2006 Avatar asked Jul 10 '18 19:07

JWH2006


1 Answers

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.

like image 60
treecon Avatar answered Nov 14 '22 13:11

treecon