Reputation: 2529
In my current R project I'm working with the ggmap
package to download and display maps.
What bothers me is that you need internet access to load maps from google etc.
I'd like to load a map from the internet and save it so I can work offline as well. An ideal solution should minimize the amount of code between get_map()
(or a related command) and using the saved map within ggmap()
(or a related command).
I know already that get_map()
has a filename
attribute to save maps as an image, and I also know the ggimage()
method (I've never actually worked with it, though.)
Is there a simple way to save such a map, or are these two the best tools available - and if so, how can I use them effectively?
Upvotes: 4
Views: 1754
Reputation: 2339
I ran into the same question after waiting for the same maps to load dozens of times per run.
You can save any object in R, but it took me a little while to figure out the nuances of saving a map inside of a function. Here's what I came up with -- would love to see if there are improvements that could be made.
The function looks for a Locale string (essentially something to name the map), coordinates, and zoom level. The function then looks to see if the map already exists as a saved file and loads it if it does. If the map doesn't exist on the disk, it is downloaded from Google and then saves it to a file.
No tricks to loading it from a file, but I found that if I didn't specify .GlobalEnv
in the assign function before saving the map object to disk, that R would faithfully load into into the wrong environment.
load.map <- function(Locale, Lon, Lat, MapZoom){
MapName <- paste("Map", gsub(" ", "", Locale), MapZoom, sep = "")
FileName <- paste(MapName,".RData", sep = "")
if (file.exists(FileName) & ReloadMaps == 0)
{
load(FileName, envir = .GlobalEnv)
} else
{
Map <- get_googlemap(center=c(lon = Lon, lat = Lat), zoom=MapZoom, scale = 2,
size = c(640, 640), maptype = "roadmap", color = "color", format = "png8")
assign(MapName, Map, envir = .GlobalEnv)
save(list = MapName, file = FileName, envir = .GlobalEnv)
}
}
Upvotes: 3