tom
tom

Reputation: 48

Leaflet change cluster marker color

I'm using ShinyProxy to deploy R ShinyApps.

I plot on a Leaflet Map marker point and cluster them because I have more than one (actually a lot) points for the same coordinates.

Each point can be in two state, so I change the color in Red or Green.

I'd like to change the color of the "cluster marker" too in:

Here a (simple dummy) photo to better explain what I mean:

example

I searched a lot but I cannot find a solution to my problem.

Here a portion of my code:

 getColor <- function(dfMap) {
            dati = lapply(dfMap$Id, function(x){ if(x %in% alarm$id){return("red")}else{ return("green")}})
            return(unlist(dati))
          }
          
          icons <- awesomeIcons(
            icon = 'ios-close',
            iconColor = 'black',
            library = 'ion',
            markerColor = getColor(dfMap)
          )
          
          map =  leaflet(dfMap,options = leafletOptions(worldCopyJump = T)) %>% addTiles() %>%
            addAwesomeMarkers(as.numeric(dfMap$lon), as.numeric(dfMap$lat), icon=icons, label=~as.character(dfMap$Id), clusterOptions = markerClusterOptions())
          
          output$alarmMap = renderLeaflet(map)

The data are a DataFrame with:

I have also another DataFrame that contains only element that should be red.

Upvotes: 0

Views: 1540

Answers (1)

det
det

Reputation: 5232

Some ideas:

including feature:

how to make appearance of clustered icon related to statistics of the children ?

change color of clusters:

How to change default CSS cluster classes ?

idea is to see if cluster has any red point/marker in it, if it has then color should be red otherwise green.

df %>%
  mutate(
    col = c(
      "green", "green", "red", "green", "green",
       "red", "green", "green"
    )
  ) %>%
  leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    options = markerOptions(col = ~col),
    color = ~col,
    clusterOptions = markerClusterOptions(
      iconCreateFunction=JS("function (cluster) {    
    var markers = cluster.getAllChildMarkers();
    var childCount = cluster.getChildCount();
    var p = 0; 
    for (i = 0; i < markers.length; i++) {
      if(markers[i].options.col === 'red'){
        p = 1;
        break;
      }
    }
    if(p === 0){
      c = 'rgba(0, 255, 0, 1);'
    } else {
      c = 'rgba(255, 0, 0, 1);'
    }
    return new L.DivIcon({ html: '<div style=\"background-color:'+c+'\"><span>' + childCount + '</span></div>', className: 'marker-cluster', iconSize: new L.Point(40, 40)});
  }")
    )
  )

data:

structure(list(lon = c(15.5898481, 15.5874236, 15.5843765, 15.5676274, 
15.5830977, 15.5701817, 15.5850915, 15.5738857), lat = c(46.9551744, 
46.9545258, 46.9556816, 46.9625003, 46.9560813, 46.9601925, 46.9539635, 
46.9586439)), row.names = c(NA, -8L), class = c("tbl_df", "tbl", 
"data.frame"))

Upvotes: 2

Related Questions