Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access map generated by leaflet in R

Tags:

r

leaflet

Let's say I have a code like this

# Install devtools if needed
if(!require(devtools)) install.packages("devtools")
# view rawif-devtools.R hosted with ❤ by GitHub
# Install leaflet package
if(!require(leaflet)) install_github("rstudio/leaflet")
library("leaflet")
mymap <- leaflet()
mymap <- addTiles(mymap)
mymap

This opens it up in Chrome with a filepath like this:

file:///var/folders/8x/v2tk5zy51x51jx9jbp0m29qr0000gn/T/RtmpQaeu1E/viewhtmlf74547061f7d/index.html. 

Let's say I want to publish this to my blog. How exactly do I access this html file? Is there a way to set where it gets saved to? I assumed it would get saved to the working directory but that isn't the case. I guess I could access it via the terminal, but I'm hoping there's an easier way.

like image 273
ytk Avatar asked May 19 '15 21:05

ytk


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.

What package is leaflet in in R?

leaflet is an open-source JavaScript library that is used to create dynamic online maps. The identically named R package makes it possible to create these kinds of maps in R as well. The syntax is identical to the mapdeck syntax. First the function leaflet() is called, followed by different layers with add*() .

What is a leaflet map?

Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 42 KB of JS , it has all the mapping features most developers ever need. Leaflet is designed with simplicity, performance and usability in mind.


1 Answers

I developed a couple of functions that lets you save a leaflet map somewhere other than a temp folder.

See the gist here: https://gist.github.com/barryrowlingson/d066a7ace15cf119681a for the full info, the short version is these two functions:

saveas <- function(map, file){
    class(map) <- c("saveas",class(map))
    attr(map,"filesave")=file
    map
}

print.saveas <- function(x, ...){
    class(x) = class(x)[class(x)!="saveas"]
    htmltools::save_html(x, file=attr(x,"filesave"))
}

then all you do is:

leaflet() %>% etc etc %>% saveas("/wherever/you/want/index.html")

or in your mode of working:

mymap <- leaflet()
mymap <- addwhatever(mymap)
saveas(mymap, "/wherever/you/want/index.html")

At that point the folder /wherever/you/want should have a self-contained set of files for the map. I think it should be portable, ie work on any web server, but I can't guarantee that...

like image 121
Spacedman Avatar answered Oct 08 '22 16:10

Spacedman