Search code examples
rr-leaflet

Print label on circle markers in leaflet


Is there any possible way to embed label on top of the circle markers in R shiny to get something like following:

enter image description here

Here is a quick example for the reference:

# Some fake data
df <- sp::SpatialPointsDataFrame(
  cbind(
    (runif(20) - .5) * 10 - 90.620130,  # lng
    (runif(20) - .5) * 3.8 + 25.638077  # lat
  ),
  data.frame(type = factor(
    ifelse(runif(20) > 0.75, "p", "s"),
    c("s", "p")
  ))
)

# leaflet map
leaflet(df) %>% addTiles() %>% addCircleMarkers(label = ~type)

I would like to print labels (i.e. 's' and 'p') on the top of the marker.


Solution

  • You need to add a labelOptions argument to your addCircleMarkers function call. By default, the labels appear as popups when you hover.

    Using your the rest of your code:

    leaflet(df) %>% addTiles() %>% addCircleMarkers(stroke = FALSE, label = ~type,
        labelOptions = labelOptions(noHide = TRUE, offset=c(0,-12), textOnly = TRUE)) 
    

    noHide = TRUE is the key

    textOnly = TRUE removes popup bubble