I am showing multiline labels in leaflet markers. Each label combines several columns of data. If if I just paste the columns together, I get one location per marker but no HTML rendering (Example 1). If I wrap the label with HTML() I get proper rendering but EVERY location is in each marker (Example 2). How do I get the desired content AND the desired formatting? Thanks.
library(htmltools)
library(leaflet)
library(dplyr)
df <- read.csv(textConnection(
"Name,Rating,Lat,Long
Samurai Noodle,Good, 47.597131,-122.327298
Kukai Ramen,Fair,47.6154,-122.327157
Tsukushinbo,Great,47.59987,-122.326726"))
# EXAMPLE 1. One location per marker but HTML not rendered
leaflet(df) %>%
addTiles() %>%
addMarkers(~Long, ~Lat,
label = ~ paste(Name,Rating,sep = "<br/>"))
# EXAMPLE 2. HTML rendered but all locations in each marker
leaflet(df) %>% addTiles() %>%
addMarkers(~Long, ~Lat,
label = ~ HTML(paste(Name,Rating,sep = "<br/>")))
Maybe there is an easier option. But one fix for your issue would be to use lapply to apply HTML on each element of your vector of labels which avoids that your labels are glued together:
library(htmltools)
library(leaflet)
library(dplyr)
df <- read.csv(textConnection(
"Name,Rating,Lat,Long
Samurai Noodle,Good, 47.597131,-122.327298
Kukai Ramen,Fair,47.6154,-122.327157
Tsukushinbo,Great,47.59987,-122.326726"
))
leaflet(df) %>%
addTiles() %>%
addMarkers(~Long, ~Lat,
label = ~lapply(paste(Name, Rating, sep = "<br>"), HTML)
)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With