Search code examples
htmlrleafletdata-visualization

Adding "Breaks" in "htmlescape"


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!


Solution

  • 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