Skip to content

Instantly share code, notes, and snippets.

@barryrowlingson
Last active May 16, 2016 14:41
Show Gist options
  • Save barryrowlingson/d066a7ace15cf119681a to your computer and use it in GitHub Desktop.
Save barryrowlingson/d066a7ace15cf119681a to your computer and use it in GitHub Desktop.
Save leaflet maps to one place and use LiveReload
'''
Maps...
Normally when using the leaflet package you do:
leaflet(data) %>% addTiles() %>% addPolygons()
and the html is saved in a new place and your web browser gets another tab appear.
After the 26th attempt to get the map right I have 25 tabs to close.
So here is a solution. This function lets you save the output to a given file and folder:
leaflet(data) %>% addTiles() %>% addPolygons() %>% saveas("/home/user/maps/index.html")
and the index file will be created there, and all the associated files and folders will
be created in that directory. Open your browser there and hit reload every time you re-run
it. One map, one tab.
'''
### load these two functions into your session
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"))
}
'''
Sick of typing reload? Get a LiveReload server. I installed a python livereload server simply
like this:
sudo pip install livereload
and run it for this map with:
livereload /home/user/maps
Now instead of browsing to the file, head for http://localhost:35729/ - you should see your map.
Rerun the leaflet() function with some new parameters, keeping the %>% saveas(....) pipe on the end.
The web page reloads all by itself. Magic.
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment