3

I create a Leaflet widget and save it locally:

library(htmlwidgets)
library(leaflet)
library(sf)

shp = st_read("/path/to/some/shapefile.shp")

m = shp %>%
  leaflet() %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  setView(lng = -70, lat = 40, zoom = 11)

saveWidget(m, "m.html")

Now I want to load this widget in a Rmarkdown chunk:

---
title: "Title"
author: "author"
date: "5/8/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

etc etc etc

```{r}
function_that_loads_widget("m.html")
```

etc etc etc

I've tried htmltools::includeHTML() but that makes the entire HTML output one big widget. The text of the report is not displayed.

I realize I could put the the code that created the Leaflet widget directly in the Rmarkdown chunk, but I don't want to do that.

ardaar
  • 1,164
  • 9
  • 19
  • 1
    `saveWidget` doesn't really do what its name suggests. It's really more like `renderWidget`. I don't think you can recover the widget from that. If you want to save an R object, use `saveRDS()` or `save()`, and read the object back with `readRDS()` or `load()`. – user2554330 May 08 '20 at 19:48
  • Why not `source` the code creating the widget directly? – Martin Schmelzer May 09 '20 at 22:09
  • @MartinSchmelzer (not OP): My use case is that I have a R script running daily to update PNG and maps and uploads them to S3. I also have a blog built using blogdown that refers to these PNG so that I don't have to rebuild the blog every day. sourcing the code would mean having to rebuild the blog and pushing to github for hosting every day. – Zoltan Jul 10 '20 at 06:32

1 Answers1

2

knitr::include_url() appears to be the solution. This works for my blogdown post.

```{r, out.width="100%"}
knitr::include_url("url_of_html", height="1080px")
```
Zoltan
  • 760
  • 4
  • 15