Art
Art

Reputation: 1225

How do I get leaflet marker labels in R to show HTML AND include label for only location of marker

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/>")))

Upvotes: 4

Views: 974

Answers (2)

ulfelder
ulfelder

Reputation: 5335

I had a similar problem in my own app that was solved by creating a column in the data frame before generating the map that includes the desired formatting. Also, for reasons I don't understand, you then pass that label to popup rather than label in the call to addMarkers(). So...

df$marker <- with(df, sprintf("%s </br> %s", Name, Rating))

leaflet(df) %>%
  addTiles() %>%
  addMarkers(~Long, ~Lat,
             popup = ~marker)

...gives what I think is the result you're looking for.

Upvotes: 1

stefan
stefan

Reputation: 124048

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)
  )

enter image description here

Upvotes: 4

Related Questions