绘制 ggmap 和 sf 点

plot ggmap and sf points

我正在努力从带有点(sf 对象)的 ggmap 中绘制底图。我遇到的最有前途的解决方案是来自@andyteucher 的 SO answer。我试图在下面重现它,但我运气不佳。我得到了要打印的底图,但没有打印点。

library(tidyverse)
library(sf)
library(ggmap)

# Define a function to fix the bbox to be in EPSG:3857
# 
  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) 

我认为您的坐标参考系统有问题 - 您似乎在 CRS 3857 的上下文中使用了度数,它以米为单位定义(因此相差几个度数...)

如果我的预感是正确的,您需要首先声明您的 sf 对象位于 4326(WGS84 = GPS 坐标的 CRS),然后 - 并且只有在那时 - 将转换应用到 3857(从已知的开始)。

这段代码和地图符合您的期望吗? (我还稍微清理了 get_map 调用,因为它混合了 Google 和 Stamen 术语;没什么大不了的)

# 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)