LabelOnlyMarkers in R Leaflet with specific colors

48 Views Asked by At

I want to build a leaflet map with CircleMarkers and LabelOnlyMarkers atop the circles. Labels and circles should have colors specified in a data.frame column.

The following does what I want, except for the coloring of the LabelOnlyMarkers. How can I change the labelOptions to plot the labels in the correct colors?

Or is there maybe an even simpler solution?


Here is my attempt:

The part style = list("color" = data$col))) does not define the colors dynamically but seems to be ignored..

library(leaflet)

data <- data.frame(lat = c(47, 48, 47), 
                   lng = c(8, 9, 10),
                   label = c("bli", "bla", "blo"),
                   col = c("#E69F00", "#56B4E9", "#009E73"),
                   stringsAsFactors = FALSE)

leaflet()  %>%
  addProviderTiles(providers$OpenStreetMap.CH, group = "OSM") %>%
  addCircleMarkers(lng = data$lng, 
                   lat = data$lat, 
                   fillColor = data$col, 
                   radius = 5, opacity = 0, fillOpacity = 1) %>%
  addLabelOnlyMarkers(lng = data$lng, 
                      lat = data$lat, 
                      label = data$label,
                      labelOptions = labelOptions(
                        noHide = T, direction = 'top', 
                        textOnly = T, textsize = "20px", 
                        style = list("color" = data$col)))

This produces:

enter image description here

... which is - apart from the black LabelOnlyMarkers - exactly what I want...

1

There are 1 best solutions below

0
sonshine On BEST ANSWER

Referencing this SO post:

# apply label w/ color as HTML
data <- data |>
    dplyr::mutate(
        lab_html = purrr::map(
            glue::glue(
                "<span style='color:{data$col}'>{as.character(data$label)}<span>"
            ),
            htmltools::HTML
        )
    )

# map
leaflet() %>%
    addProviderTiles(providers$OpenStreetMap.CH, group = "OSM") %>%
    addCircleMarkers(
        lng = data$lng,
        lat = data$lat,
        fillColor = data$col,
        radius = 5, opacity = 0, fillOpacity = 1
    ) %>%
    addLabelOnlyMarkers(
        lng = data$lng,
        lat = data$lat,
        label = data$lab_html,
        labelOptions = labelOptions(
            noHide = TRUE, direction = "top",
            textOnly = TRUE, textsize = "20px"
        )
    )

Yields:

map

Hope that helps!