在{ggspatial}的annotation_spatial中使用WMS底图报错求助
在{ggspatial}中使用WMS底图的问题解决
问题描述
想在{ggspatial}中用WMS作为底图,但遇到两个问题:
- 用{terra}能读取WMS并通过
plotRGB正常显示正射影像,但{stars}无法直接读取该WMS - 将{terra}读取的SpatRaster对象传入
annotation_spatial时触发错误
相关代码及报错
library(ggspatial) library(sf) library(terra) library(stars) library(ggplot2) points <- data.frame( id = 1:5, x = (436:440)*1e3, y = (4670:4674)*1e3 ) |> st_as_sf(coords = c("x", "y"), crs = 25831) box <- st_bbox(points) wms <- paste0("https://geoserveis.icgc.cat/servei/catalunya/orto-territorial/wms?REQUEST=GetMap&VERSION=1.3.0&SERVICE=WMS&CRS=EPSG:25831&BBOX=",box[1],",",box[2],",",box[3],",",box[4],"&WIDTH=520&HEIGHT=520&LAYERS=ortofoto_color_vigent&STYLES=&FORMAT=JPEG&BGCOLOR=0xFFFFFF&TRANSPARENT=TRUE&EXCEPTION=INIMAGE") orto <- rast(wms) plotRGB(orto) # 正射影像可正常显示 ggplot() + annotation_spatial(orto) + layer_spatial(points) # 报错信息: # Error in `layer_spatial.SpatRaster()`: # ! Problem while converting geom to grob. # ℹ Error occurred in the 1st layer. # Caused by error: # ! vector::reserve
解决方案
方法1:将SpatRaster转换为stars对象后使用
虽然直接用stars读取WMS失败,但可以先通过terra读取,再转换为stars格式:
orto_stars <- st_as_stars(orto) ggplot() + annotation_spatial(orto_stars) + layer_spatial(points)
方法2:调整栅格通道顺序或数据类型
部分情况下,RGB栅格的通道顺序(如BGR)会导致ggspatial处理出错,可手动调整通道顺序:
# 确保通道为RGB顺序,若原数据是BGR则改为c(3,2,1) orto_rgb <- orto[[c(1,2,3)]] ggplot() + annotation_spatial(orto_rgb) + layer_spatial(points)
方法3:用annotation_map_tile直接加载WMS(推荐)
ggspatial自带的annotation_map_tile可直接处理WMS请求,无需手动读取栅格,避免格式转换问题:
ggplot() + annotation_map_tile( type = "https://geoserveis.icgc.cat/servei/catalunya/orto-territorial/wms?", layer = "ortofoto_color_vigent", style = "", format = "image/jpeg", crs = 25831, parameters = list( VERSION = "1.3.0", BGCOLOR = "0xFFFFFF", TRANSPARENT = TRUE ) ) + layer_spatial(points)
内容的提问来源于stack exchange,提问作者Josep Pueyo
相关产品推荐
相关产品推荐

