R code to save shiny.tag.list to html as the viewer->export->save as web page button does

1.4k Views Asked by At

I have a leaflet map that I have modified to have a special CSS for popups following the suggestions here. Now I want to save the result as an HTML web page. The resulting object is of type shiny.tag.list, which I can view with the viewer and export to HTML by hand using the Export->Save as web page button. However, I cannot find the R code to do this same operation. I have tried the mapshot function in the mapview package and the saveWidget function in htmltools, but these fail with the error:

> saveWidget(lf,"test.html")
Error in .getNamespace(pkg) : 
 invalid type/length (symbol/0) in vector allocation

I have also tried the save_html function of the htmltools package, but this generates an HTML file that is not standalone.

How do I do exactly what the Export->Save as web page button does with R code?

Here is some sample code to demonstrate the issues:

library(sf)
library(leaflet)
library(htmltools)
library(mapview)

x = data.frame(lat=c(44,45),lon=c(3,2),
               label=c("p1","p2"))

x = st_as_sf(x,coords=c("lon","lat"),crs=4326)

lf = x %>% leaflet %>% addTiles() %>% addMarkers(label=~label,popup=~label)
st = browsable(
  tagList(list(
    tags$head(
      tags$style(".leaflet-popup-content-wrapper {background-color: #ff0000;}")
    ),
    lf
  ))
)

saveWidget(st,"test.html") # Fails with error
mapshot(st,"test.html") # Fails with same error
save_html(st,"test.html") # Produces HTML with external dependencies
1

There are 1 best solutions below

0
On

I ran into the same problem and solved it with htmlwidgets::prepandContent

library(sf)
library(leaflet)
library(htmltools)
library(mapview)
library(htmlwidgets)

x = data.frame(lat=c(44,45),lon=c(3,2),
               label=c("p1","p2"))

x = st_as_sf(x,coords=c("lon","lat"),crs=4326)

lf = x %>% leaflet %>% addTiles() %>% addMarkers(label=~label,popup=~label)


st = lf %>% prependContent(
    tags$head(
      tags$style(".leaflet-popup-content-wrapper {background-color: #ff0000;}")
    )
    )

saveWidget(st,"test.html") # works!