I'm making an R Shiny app with Leaflet that shows trees in a city. I want to add an svg image to the marker popups that depends on the tree species for the clicked marker, but I can't get includeHTML to work.
circle.svg:
<svg width = "20" height = "20"
xmlns="http://www.w3.org/2000/svg">
<circle cx="10" cy="10" r="10" style="fill:#000;"/>
</svg>
square.svg:
<svg width = "20" height = "20"
xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width = "20" height = "20" style="fill:#000;"/>
</svg>
When I run the code below, I get an error:
library(shiny)
library(leaflet)
library(tidyverse)
library(magrittr)
df <- data.frame("type" = c("circle", "square"),
"lon" = c(13.36, 13.37),
"lat" = c(52.56, 52.57)
)
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output) {
output$map <- renderLeaflet({
leaflet(df) %>%
addTiles() %>%
addCircleMarkers(
popup = ~ paste0(type, ": ", includeHTML(paste0(type, ".svg")))
)
})
}
shinyApp(ui = ui, server = server)
Warning: Error in file: invalid 'description' argument
119: file
118: readLines
117: includeHTML
...
But if remove includeHTML, the filenames are written correctly in the popups.
popup = ~ paste0(type, ": ", paste0(type, ".svg"))
If I index type
, includeHTML works fine, expect it shows the circle in both popups, which is of course not what I want:
popup = ~ paste0(type, ": ", includeHTML(paste0(type[1], ".svg")))
It seems the includeHTML takes the whole df$type
vector instead of just the one element of the vector that is relevant to the marker.
What is going on, and how can I solve this?
You can generate your popups using
sapply(type, function(x) paste0(x, ": ", includeHTML(paste0(x, ".svg"))))
as follows:
ui <- fluidPage(
leafletOutput("map")
)
server <- function(input, output) {
output$map <- renderLeaflet({
leaflet(df) %>%
addTiles() %>%
addCircleMarkers(
popup=~sapply(type, function(x) paste0(x, ": ", includeHTML(paste0(x, ".svg"))))
)
})
}
shinyApp(ui = ui, server = server)