luciano luciano - 1 month ago 20
R Question

Cache maps using ggmap

I'm plotting maps using the

ggmap
package. To download a map over the internet, I can use this code:

library(ggmap)
get_map(location = c(-1.81, 55.655), zoom = 12, maptype = "hybrid")


Is there a way to avoid downloading maps over the internet, and instead import a .png file from a local folder? Or in other words, download maps once, cache the .png and thereafter import the .png from a local folder? My connection is rather slow, I constantly redownloading the same base map is wasting valuable time.

Answer

As get_map returns an R object, you can save that to disk and reuse later if you wish:

> x <- get_map(location = c(-1.81, 55.655), zoom = 12, maptype = "hybrid")
Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=55.655,-1.81&zoom=12&size=%20640x640&scale=%202&maptype=hybrid&sensor=false
Google Maps API Terms of Service : http://developers.google.com/maps/terms
> str(x)
 chr [1:1280, 1:1280] "#122C38" "#122C38" "#122C38" "#122C38" ...
 - attr(*, "class")= chr [1:2] "ggmap" "raster"
 - attr(*, "bb")='data.frame':  1 obs. of  4 variables:
  ..$ ll.lat: num 55.6
  ..$ ll.lon: num -1.92
  ..$ ur.lat: num 55.7
  ..$ ur.lon: num -1.7

So simply write x to your disk with saveRDS, and load that via readRDS even from another R session. POC demo:

> t <- tempfile()
> saveRDS(x, file = t)
> x <- readRDS(t)
> ggmap(x)
Comments