ytk ytk - 1 year ago 93
R Question

How to access map generated by leaflet in R

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")
mymap <- leaflet()
mymap <- addTiles(mymap)

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


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.

Answer Source

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

See the gist here: for the full info, the short version is these two functions:

saveas <- function(map, file){
    class(map) <- c("saveas",class(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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download