markersshinyjsr-leafletbringtofront

Bring a group of markers to front in leaflet


I am attempting to map some densely-located locations on leaflet in rShiny with awesomeMarkers. I have tried a variety of methods, but what I would like is to have a certain group of markers appear above other markers. I have provided a small example dataset below and, essentially, what I would like, is that when zoomed out, the red markers appear above the blue markers, so that the red markers are always visible and never hidden by the blue markers (even when zoomed fairly far out).

I have been doing some research both on SO as well as other forums, but have not yet been able to find any answers. Thanks so much for any help!

 Name      lat      lng group
    A 45.42901 6.616382  blue
    B 45.50991 6.690683   red
    C 45.57084 6.820715  blue
    D 45.32330 6.538921   red
    E 45.39663 6.565520  blue
    F 45.46781 6.904085   red
    G 45.28815 6.903484  blue
    H 45.29815 6.582392   red
    I 45.44571 6.976880  blue
    J 45.46178 6.442174   red

Also, here is the code I have so far:

icons = awesomeIcons(
  icon = 'asterisk',
  iconColor = "darkblue",
  library = "fa",
  markerColor = example$group
)

leaflet(example) %>% addTiles() %>% addAwesomeMarkers(icon = icons) 

Solution

  • You can add options to the markers using options = markerOptions(...) and markerOptions() has a zIndexOffset.

    We can set it to a high value to make those marker above the others. We can get an integer casting to factor and to integer a string. Or you can add another columns, that's up to you.

    marker_options <- markerOptions(
      zIndexOffset = as.integer(as.factor(df$group)) * 100
    )
    

    One important thing is to make the difference between groups high (I think because the index increments with each marker and this is actually a rescale factor or something along this lines.

    The final map should be:

    library(leaflet)
    library(dplyr)
    
    icons = awesomeIcons(
      icon = 'asterisk',
      iconColor = "darkblue",
      library = "fa",
      markerColor = df$group
    )
    
    marker_options <- markerOptions(
      zIndexOffset = as.integer(df$group) * 100
    )
    
    
    df %>% 
      leaflet() %>%
      addTiles() %>%
      addAwesomeMarkers(
        icon = icons,
        options = marker_options
      )
    

    leaflet map zoomed out