使用R的ggmap加载Stamen塞浦路斯地图报错,求解决办法
解决ggmap获取塞浦路斯地图的错误及替代方案
一、核心问题原因
- Stamen瓦片已迁移至Stadia Maps托管,原
tile.stamen.com域名已停用,新版ggmap需使用Stadia API密钥并调用新函数。 - 你使用的UTM坐标(36N)与ggmap地图接口要求的WGS84经纬度不兼容,需先转换坐标。
二、修复步骤(基于新版ggmap)
1. 获取并配置Stadia API密钥
- 前往Stadia Maps平台注册账号,获取免费API密钥(个人免费额度足够日常使用)。
- 在R中注册密钥:
library(ggmap) register_stadiamaps("你的Stadia API密钥")
2. 转换坐标至WGS84经纬度
你的bbox是UTM 36N坐标系(CRS: 32636),需转换为WGS84(CRS: 4326),用sf包实现:
library(sf) # 定义原始UTM坐标的CRS utm_crs <- st_crs(32636) # 创建UTM坐标系下的bbox多边形 cy_bbox_utm <- st_sfc(st_polygon(list(rbind( c(leftCY, bottomCY), c(rightCY, bottomCY), c(rightCY, topCY), c(leftCY, topCY), c(leftCY, bottomCY) ))), crs = utm_crs) # 转换为WGS84经纬度 cy_bbox_wgs84 <- st_transform(cy_bbox_utm, st_crs(4326)) # 提取经纬度范围 bbox_wgs84 <- st_bbox(cy_bbox_wgs84)
3. 调用新版函数获取地图
使用get_stadiamap替代get_stamenmap,maptype参数需添加stamen_前缀:
RHO_map <- get_stadiamap( bbox = c(left = bbox_wgs84$xmin, bottom = bbox_wgs84$ymin, right = bbox_wgs84$xmax, top = bbox_wgs84$ymax), zoom = 10, maptype = "stamen_terrain" ) # 绘制地图 ggmap(RHO_map)
三、替代方案(无需API密钥)
如果不想依赖Stadia API,可使用osmdata包直接从OpenStreetMap获取矢量地图数据,配合ggplot2绘制:
library(osmdata) library(ggplot2) # 用经纬度bbox获取OSM基础地图数据 cy_osm <- opq(bbox = c(bbox_wgs84$xmin, bbox_wgs84$ymin, bbox_wgs84$xmax, bbox_wgs84$ymax)) %>% add_osm_feature(key = "natural", value = c("water", "land")) %>% add_osm_feature(key = "highway") %>% osmdata_sf() # 绘制地图 ggplot() + geom_sf(data = cy_osm$osm_polygons[cy_osm$osm_polygons$natural == "land",], fill = "#f0e6d6") + geom_sf(data = cy_osm$osm_polygons[cy_osm$osm_polygons$natural == "water",], fill = "#a3d2e2") + geom_sf(data = cy_osm$osm_lines, color = "#666666", size = 0.3) + coord_sf(xlim = c(bbox_wgs84$xmin, bbox_wgs84$xmax), ylim = c(bbox_wgs84$ymin, bbox_wgs84$ymax)) + theme_minimal()
内容的提问来源于stack exchange,提问作者ΚΩΝΣΤΑΝΤΙΝΟΣ ΠΑΝΑΓΙΩΤΟΥ
相关产品推荐
相关产品推荐

