0

Using the quakes data as an example, I want to assign a random colour to each station in the dataset, use marker clustering, and have icons with the colour in the layer control.

I have managed to do the first part (see code below), but now I want to add icons with the right colours to the layer control next to the station ID.

Can anyone please help me?

Thank you!!

library(leaflet)
data(quakes)
quakes<-head(quakes,10)
quakes$stations<-as.factor(quakes$stations)
map<-leaflet()
map<-addTiles(map,group = "OSM (default)")
map<-addProviderTiles(map,providers$Stamen.Toner, group = "Toner")
map<-addProviderTiles(map,providers$Stamen.TonerLite, group = "Toner Lite")
stations<-unique(quakes$stations)
marker_colours<-rainbow(length(stations))
for (station in 1:length(stations)){        
    filtered_map_station<-quakes[quakes$stations==stations[station],]
    col_as_RGB<-paste(c(as.vector(col2rgb(marker_colours[station])),0.6), collapse = ",")       
    map<-addMarkers(map,filtered_map_station$lon, filtered_map_station$lat, group = stations[station],
        clusterOptions = markerClusterOptions(maxClusterRadius = 5,transparent=TRUE,singleMarkerMode=TRUE,zoomToBoundsOnClick=FALSE,
            iconCreateFunction=JS(paste0("function(cluster) {
                var c = ' marker-cluster-small';
                var html = '<div style=\"background-color:rgba(",col_as_RGB,")\"><span>' + cluster.getChildCount() + '</div><span>'
                return new L.DivIcon({html: html, className: 'marker-cluster' + c,iconSize: new L.Point(40, 40) });
            }"))
        )
    )   
}   
map<-addLayersControl(map,
    baseGroups = c("OSM (default)", "Toner", "Toner Lite"),
    overlayGroups = stations,
    options = layersControlOptions(collapsed = FALSE)
)
map
Esteban
  • 13
  • 3
  • This might lead you in the right direction https://stackoverflow.com/questions/47227557/add-icons-to-layer-control-in-leaflet-r – rbasa Sep 27 '21 at 10:40
  • Thank you, in fact I already tried out the accepted answer in that post, and while it works for the colours in the example given, it fails when one changes the colours! – Esteban Sep 28 '21 at 17:50

0 Answers0