Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save Leaflet in R map as png or jpg file?

Tags:

r

leaflet

I'm using Leaflet package to create maps in R. It works perfectly. I can export maps in R with simply Export, but I need to export maps from script in R. My simple code is:

png("test_png.png") (m <- leaflet() %>% addTiles()) dev.off() 

It works but... the output png file is white blank.

like image 720
sms Avatar asked Jul 10 '15 09:07

sms


People also ask

How do you save a map on leaflet?

Yes, you can save leaflet objects as images. In the viewer tab, above the map, you will find an export button to save leaflets as an image.

Which is the default map tile in leaflet package?

Default (OpenStreetMap) Tiles.


1 Answers

This very nice workaround emerged in response to a question asked a little later here on SO. Note that you are required to install PhantomJS to get the following code to work.

## install 'webshot' package library(devtools) install_github("wch/webshot")  ## load packages library(leaflet) library(htmlwidgets) library(webshot)  ## create map m <- leaflet() %>% addTiles()  ## save html to png saveWidget(m, "temp.html", selfcontained = FALSE) webshot("temp.html", file = "Rplot.png",         cliprect = "viewport") 

And here's the resulting image.

map


Update:

Now that webshot has been officially released on CRAN and with the introduction of mapshot in the mapview package, this manual workaround is no longer required. Now, the code simply goes like this:

library(mapview)  ## 'leaflet' objects (image above) m <- leaflet() %>% addTiles() mapshot(m, file = "~/Rplot.png")  ## 'mapview' objects (image below) m2 <- mapview(breweries91) mapshot(m2, file = "~/breweries.png") 

breweries

like image 200
fdetsch Avatar answered Sep 26 '22 02:09

fdetsch