How to write/share an html document created in R using crosstalk and leaflet

41 views Asked by At

I've created a filterable map using crosstalk and leaflet in R, and I'd like to share this with coworkers as a standalone document:

library(leaflet)
library(htmltools)
library(htmlwidgets)

#example data
df <-data.frame("A"=c("a","b","c"),
            "Lat"=c( 40.471737,40.495716,40.402972),
            "Lon"=c(-100.863312,-100.934637,-100.859008))

#convert dataframe to shared data object for crosstalk
df$A <- as.factor(df$A)
df_shared <- SharedData$new(df)

#create map with shared data
map <- leaflet(df_shared)%>%
leaflet::addTiles(url 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryTopo/MapServer/tile/{z}/{y}/{x}', group = "Hybrid")%>% #
addCircleMarkers()

#Merge filter with map using bscols  
final <- bscols(widths = c(1,11),
            filter_select(id="A", label="Filter", sharedData=df_shared, group=~A), 
            map
)
final 

The filterable map (final) works fine in the viewer pane in rStudio and also when I write it out to my local machine using:

 html_tools::save_html(final, file="final.html") 

However when I send this file to someone else the dependencies are not attached (meaning save_html does not write to a standalone document). When I export the final map using the export as html from the viewer pane all data and functionality works as it should even when sent to another device.

My question is, is there any way to script the viewer export as html function so I can keep all dependencies when writing out a standalone html document?

Note that htmlwidgets::saveWidget() does not work for the object created by bscols.

1

There are 1 answers

0
Chris Newton On

Could be a good use case for {flexdashboard}, which could be knit to an HTML document you could share. Something like:

---
title: "Example"
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(leaflet)
library(htmltools)
library(htmlwidgets)
library(crosstalk)

#example data
df <-data.frame("A"=c("a","b","c"),
            "Lat"=c( 40.471737,40.495716,40.402972),
            "Lon"=c(-100.863312,-100.934637,-100.859008))

#convert dataframe to shared data object for crosstalk
df$A <- as.factor(df$A)
df_shared <- SharedData$new(df)

#create map with shared data
map <- leaflet(df_shared) |> 
leaflet::addTiles() |> 
addCircleMarkers()
```

Column {data-width=350}
-----------------------------------------------------------------------
### Filter

```{r}
filter_select(id="A", label="Filter", sharedData=df_shared, group=~A)
```

Column {data-width=650}
-----------------------------------------------------------------------

### Map
```{r}
map
```