使用ggmap缓存地图

5

我正在使用ggmap包制作地图。要从互联网下载地图,我可以使用以下代码:

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

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

2个回答

7

由于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

所以,只需使用 saveRDSx 写入您的磁盘,并通过 readRDS 从另一个 R 会话中加载即可。POC演示:

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

6

自从提问以来已经过去了2年多的时间,新版本的ggmap已经推出。该包现在直接支持下载缓存。然而,在缓存Google地图时,有些条件需要注意;当附加ggmap时,会出现一条链接到服务条款的链接。

通用的get_map函数没有保存下载的Google地图瓦片的选项,但是可以通过专门的get_googlemap函数来实现,将archiving = TRUE设置为真。手册中有一条关于用户在这种情况下(也)必须接受Google Maps服务条款的注意事项。在我看来,服务条款(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

其他地图来源可能具有更宽松的条款或许可证。例如,使用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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接