我正在努力用点(sf对象)从ggmap绘制一个基本地图。我遇到的最有希望的解决方案是@andyteucher的SO answer。我试着把它复制到下面,但运气不太好。我把基本地图打印出来,但不打印要点。
library(tidyverse)
library(sf)
library(ggmap)
# Define a function to fix the bbox to be in EPSG:3857
# https://stackoverflow.com/a/50844502/841405
ggmap_bbox <- function(map) {
if (!inherits(map, "ggmap")) stop("map must be a ggmap object")
# Extract the bounding box (in lat/lon) from the ggmap to a numeric vector,
# and set the names to what sf::st_bbox expects:
map_bbox <- setNames(unlist(attr(map, "bb")),
c("ymin", "xmin", "ymax", "xmax"))
# Coonvert the bbox to an sf polygon, transform it to 3857,
# and convert back to a bbox (convoluted, but it works)
bbox_3857 <- st_bbox(st_transform(st_as_sfc(st_bbox(map_bbox, crs = 4326)), 3857))
# Overwrite the bbox of the ggmap object with the transformed coordinates
attr(map, "bb")$ll.lat <- bbox_3857["ymin"]
attr(map, "bb")$ll.lon <- bbox_3857["xmin"]
attr(map, "bb")$ur.lat <- bbox_3857["ymax"]
attr(map, "bb")$ur.lon <- bbox_3857["xmax"]
map
}
# requires API key
basemap <- get_map(location=c(lon = 75.85199398072335,
lat = 22.7176905515565),
zoom=9, maptype = 'toner-hybrid',
source = 'google')
basemap_3857 <- ggmap_bbox(basemap)
points <- tribble(
~name, ~lat, ~lon,
"test1", 22.7176905515565, 75.85199398072335,
"test2", 22.71802612842761, 75.84848927237663,
) %>%
st_as_sf(coords = c("lat", "lon"),
crs = 3857)
ggmap(basemap_3857) +
coord_sf(crs = st_crs(3857)) +
geom_sf(data = points,
inherit.aes = FALSE) 发布于 2021-12-14 08:52:16
我相信你的坐标参考系统有问题-你似乎在CRS 3857中使用了学位,CRS 3857是以米为单位定义的(所以有几个震级.)
如果我的预感是正确的,您需要首先声明您的sf对象在4326 (WGS84 =全球定位系统坐标的CRS ),然后(然后)应用转换到3857 (从一个已知的开始)。
这些代码和地图是否符合您的期望?(我还在一定程度上清理了get_map电话,因为它混淆了谷歌和斯塔门的术语,没有什么大不了的。)
# requires API key
basemap <- get_map(location=c(lon = 75.85199398072335,
lat = 22.7176905515565),
zoom=9,
source = 'google')
basemap_3857 <- ggmap_bbox(basemap)
points <- tribble(
~name, ~lat, ~lon,
"test1", 22.7176905515565, 75.85199398072335,
"test2", 22.71802612842761, 75.84848927237663,
) %>%
st_as_sf(coords = c("lon", "lat"),
crs = 4326) %>% # this is important! first declare wgs84
st_transform(3857) # and then transform to web mercator
ggmap(basemap_3857) +
geom_sf(data = points,
color = "red",
inherit.aes = F)

https://stackoverflow.com/questions/70337882
复制相似问题