45
votes

I am using RStudio to create some some leaflet images.

I would like to be able to save the output as an HTML so that it can be emailed and others can view it.

Below is some sample R code which was taken from [here] to create a sample leaflet image.

devtools::install_github('rstudio/leaflet')
library(leaflet)
rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
m = leaflet() %>% addTiles() %>% addCircles(rand_lng(50), rand_lat(50), radius = runif(50, 10, 200))
m

Any code to be able to the output as HTML would be much appreciated...

6
saveWidget is the way to go (as user1825941answered). if you want to make bitmaps, github.com/tesseradata/trelliscope/blob/master/R/thumb.R is the other way to go.hrbrmstr

6 Answers

78
votes

Something like:

library(htmlwidgets)
saveWidget(m, file="m.html")

seems to work on most widgets.

11
votes

Open a new RMarkdown document. When you are using RStudio go to File -> New File -> R Markdown. Once you saved the file, you can insert your code into a chunk, like this:

---
title: "Leaflet Map"
output: html_document
---

```{r}
library(leaflet)
rand_lng = function(n = 10) rnorm(n, -93.65, .01)
rand_lat = function(n = 10) rnorm(n, 42.0285, .01)
m = leaflet() %>% addTiles() %>% addCircles(rand_lng(50), rand_lat(50), radius = runif(50, 10, 200))
m
```

Then Press the Knit HTML Button above the code window and your application will open in a new HTML file. You can send the file via eMail or upload it to your ftp.

3
votes

I have faced the same problem and after installing Github version the problem was fixed.

# Or Github version
if (!require('devtools')) install.packages('devtools')
devtools::install_github('rstudio/leaflet')

My present version is 1.1.0.9000, running on macOS Sierra, RStudio Version 1.1.232 and R 3.4.0

You can export from RStudio or save using htmlwidgets.

2
votes

Another option using mapview library is:

library(mapview) mapshot(m, url = "m.html")

Note that you can also set the output to .png, .pdf, or .jpeg.

0
votes

library(mapview)

To save as a "png" or "jpg" image:

mapshot(m, file = "m.png")
mapshot(m, file = "m.jpeg")

Even pdf can be used

0
votes

Both solutions saveWidget or mapshot work correctly (saveWidget seems to be quicker), however, you should take care with color selection, especially in those choosed for borders/lines of polygons because in the stored map not all colours in borders are drawn ("grey50" for example is ignored while pure colours as "black" are drawn normally).

Curiously, these colours are stored and shown correctly when they are used as fill colour.