1

I am following this tutorial here (https://rstudio.github.io/leaflet/popups.html):

library(htmltools)
library(leaflet)

df <- read.csv(textConnection(
    "Name,Lat,Long
Samurai Noodle,47.597131,-122.327298
Kukai Ramen,47.6154,-122.327157
Tsukushinbo,47.59987,-122.326726"
))

leaflet(df) %>% addTiles() %>%

    addMarkers(~Long, ~Lat, popup = ~htmlEscape(Name))

Now, I want to the popups to display the information about the name, the longitude and the latitude (i.e. title + value) - I would like it to say:

  • Name = Insert Restaurant Name Here
  • (new line)
  • Longitude = Insert Longitude Name Here
  • (new line)
  • Latitude = Insert Latitude Here

I thought that this could be done as follows:

leaflet(df) %>% addTiles() %>%

addMarkers(~Long, ~Lat, popup = ~htmlEscape(df$Name, df$Lat, df$Long))

But this is giving me the following error:

Error in htmlEscape(df$Name, df$Lat, df$Long) : unused argument (df$Long)

I tried to read about this function (https://www.rdocumentation.org/packages/htmltools/versions/0.5.2/topics/htmlEscape), but there does not seem to be too much information on how to use it. I thought that maybe this might require "combining" all the arguments together:

leaflet(df) %>% addTiles() %>%

addMarkers(~Long, ~Lat, popup = ~htmlEscape(c(df$Name, df$Lat, df$Long)))

But now this only displays the final argument (and that too, without the title).

  • Is "htmlescape()" able to handle multiple arguments?

Thank you!

3
  • 1
    You need to combine the values yourself. Use paste() rather than c(): addMarkers(~Long, ~Lat, popup = ~htmlEscape(paste(Name, Lat, Long)))
    – MrFlick
    Commented Jul 31, 2022 at 20:29
  • @ MrFlick: thank you for your reply! Is there a way to add "breaks" in the popup for new lines? e.g. addMarkers(~Long, ~Lat, popup = ~htmlEscape(paste(Name <br>, Lat <br>, Long)))
    – stats_noob
    Commented Jul 31, 2022 at 20:53
  • Is it also possible to add the titles for each one, e.g. Name = Name, Lat = Lat, Long = Long? thank you so much!
    – stats_noob
    Commented Jul 31, 2022 at 20:53

1 Answer 1

1

I've not been able to pass html breaks into the ~htmlEscape() function directly.

What has worked for me is constructing the popup information as a column within the object being passed to leaflet. The new column is called directly into the popup parameter of the object.

library(leaflet)
library(dplyr)

df <- read.csv(textConnection(
  "Name,Lat,Long
Samurai Noodle,47.597131,-122.327298
Kukai Ramen,47.6154,-122.327157
Tsukushinbo,47.59987,-122.326726"
))%>%
  dplyr::mutate(popup = paste0("Name:", Name,
                               "<br/>Lat:", Lat,
                               "<br/>Lat:", Long))

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

enter image description here

Not the answer you're looking for? Browse other questions tagged or ask your own question.