Skip to content

Instantly share code, notes, and snippets.

@tim-salabim
Created March 10, 2020 18:30
Show Gist options
  • Save tim-salabim/e9672ecc696af70ef2dc87eee04ea840 to your computer and use it in GitHub Desktop.
Save tim-salabim/e9672ecc696af70ef2dc87eee04ea840 to your computer and use it in GitHub Desktop.
Use {later} to watch for sf objects and automatically mapview them
# This will watch your global environment for sf objects and mapview them automagically.
library(later)
library(mapview)
last_value = NULL
dir <- tempfile()
dir.create(dir)
htmlFile <- file.path(dir, "index.html")
get_sf_data = function() {
dat = ls(envir = .GlobalEnv)
cls = lapply(lapply(dat, get), class)
spatdat = dat[grep("sf", cls)]
lapply(spatdat, get)
}
mv_watch = function() {
spatdat_lst = get_sf_data()
if (length(spatdat_lst) > 0 && !identical(spatdat_lst, last_value)) {
m = mapview(spatdat_lst)
mapshot(m, htmlFile)
# (code to write some content to the file)
rstudioapi::viewer(htmlFile)
last_value <<- spatdat_lst
}
later::later(mv_watch, 0.25)
}
## initiate the watcher
mv_watch()
library(sf)
nc = st_read(system.file("shape/nc.shp", package="sf"))
nc = nc[, 1]
@tim-salabim
Copy link
Author

Peek 2020-03-10 19-25

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment