使用ggmap缓存地图

luc*_*ano 5 caching r ggplot2 ggmap

我正在使用ggmap包绘制地图.要通过互联网下载地图,我可以使用以下代码:

library(ggmap)
get_map(location = c(-1.81, 55.655), zoom = 12, maptype = "hybrid")
Run Code Online (Sandbox Code Playgroud)

有没有办法避免通过互联网下载地图,而是从本地文件夹导入.png文件?或者换句话说,下载地图一次,缓存.png,然后从本地文件夹导入.png?我的连接速度很慢,我不断重新加载相同的基本地图浪费了宝贵的时间.

dar*_*zig 6

get_map返回一个R对象时,您可以将其保存到磁盘并在以后重复使用,如果您愿意:

> 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
Run Code Online (Sandbox Code Playgroud)

所以只需用x你的磁盘写入saveRDS,然后通过readRDS另一个R会话加载它.POC演示:

> t <- tempfile()
> saveRDS(x, file = t)
> x <- readRDS(t)
> ggmap(x)
Run Code Online (Sandbox Code Playgroud)


mvk*_*pel 6

在提出问题之后的2年多时间里,ggmap已经出现了新的版本.该软件包现在直接支持下载缓存.但是,在缓存Google地图时,应该注意一些条件; ggmap附加时会显示指向服务条款的链接.

常规get_map功能没有保存下载的Google地图图块的选项,但可以get_googlemap通过设置使用专用功能完成archiving = TRUE.手册中有关于用户必须接受Google地图服务条款(ToS)的说明(也是).在我看来,ToS(2015年9月21日)中最明显的限制是地图内容不得存储超过30天.如果您接受,则以下代码应该有效.

library(ggmap)
## get_map() as in the question
foo1 <- get_map(location = c(-1.81, 55.655), zoom = 12, maptype = "hybrid")

## This will store map tiles locally, used by any repeated calls
foo2 <- get_googlemap(center = c(-1.81, 55.655), zoom = 12,
                      maptype = "hybrid", archiving = TRUE, force = FALSE)

identical(foo1, foo2) # TRUE
Run Code Online (Sandbox Code Playgroud)

其他地图来源可能有更多的许可条款或许可.例如,要使用Stamen Maps:

## Get roughly the same area as in the Google map
bbox <- c(left=-1.88, bottom=55.625, right=-1.74, top=55.685)
## Broken in ggmap 2.6.1, try GitHub version (which may have other problems)
foo3 <- get_map(location = bbox, zoom = 13, crop = FALSE,
                source = "stamen", maptype = "terrain", force = FALSE)

## Compare the two map sources / types
dev.new()
print(ggmap(foo2))
dev.new()
print(ggmap(foo3))
Run Code Online (Sandbox Code Playgroud)