9
votes

How do I customize the coloring of the addMarkers function in the leaflet package for R?

The default coloring for clusters is:

  • 1-10 Green
  • 11-100 Yellow
  • 100+ Red

I'd like to change the ranges and colors to something like:

  • 1-100 Red
  • 101-1000 Yellow
  • 1000+ Green

JS Leaflet has this capability: https://github.com/Leaflet/Leaflet.markercluster#customising-the-clustered-markers

Is this possible through a markerClusterOptions parameter in the R package?

leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions()
)
1
not quite the same, but I recently wanted to do the same thing and found that the github version had recently added the option to make custom icons, so you can at least color the markers easily.Rorschach

1 Answers

12
votes

You can use the iconCreateFunction in the markerClusterOptions to create your own custom icon function to display the cluster markers.

In your example, you can maybe just modify the default marker function (found here) and just modify the if/else loops setting the CSS class of the markers. The default CSS that colors the markers can be found here. You can create your own classes if you want more customisation.

Here's a code example (large is red coloring, medium is yellow, and small is green so I just switched the default code around to match your conditions):

library(leaflet)
leaflet(quakes) %>% addTiles() %>% addMarkers(
  clusterOptions = markerClusterOptions(iconCreateFunction=JS("function (cluster) {    
    var childCount = cluster.getChildCount(); 
    var c = ' marker-cluster-';  
    if (childCount < 100) {  
      c += 'large';  
    } else if (childCount < 1000) {  
      c += 'medium';  
    } else { 
      c += 'small';  
    }    
    return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });

  }"))
)