luciano luciano - 1 year ago 122
R Question

Cache maps using ggmap

I'm plotting maps using the

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

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 Source

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 :,-1.81&zoom=12&size=%20640x640&scale=%202&maptype=hybrid&sensor=false
Google Maps API Terms of Service :
> 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:
  ..$ num 55.6
  ..$ ll.lon: num -1.92
  ..$ 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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download