You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot绘制Native Land地理数据报错的解决咨询

解决Native Land GeoJSON在sf/ggplot2中右手定则错误的方案

问题根源

Native Land提供的indigenousTerritories.json存在多边形方向不符合OGC右手定则的问题(外多边形应为逆时针、内洞为顺时针),sf和ggplot2对几何格式校验更严格,因此抛出转换错误;而leaflet的GeoJSON解析器容错性较高,所以能正常加载。

有效使用方案

方案1:修复几何对象后用于sf/ggplot2可视化

使用sf的st_make_valid()函数自动修正多边形方向及其他几何有效性问题:

library(leaflet)
library(sf)
library(ggplot2)

url <- "https://native-land.ca/coordinates/indigenousTerritories.json" 
# 静默读取避免冗余输出
NL <- sf::st_read(url, quiet = TRUE)

# 修复几何有效性,自动调整多边形方向
NL_valid <- sf::st_make_valid(NL)

# 正常绘制ggplot地图
ggplot(NL_valid) + 
  geom_sf(fill = "cornflowerblue", alpha = 0.4, color = "#333", linewidth = 0.5) +
  theme_minimal()

方案2:基于leaflet扩展自定义要素

既然leaflet能直接加载该GeoJSON,可直接在现有地图基础上添加自定义要素(标记、多边形等):

library(leaflet)
library(jsonlite)

url <- "https://native-land.ca/coordinates/indigenousTerritories.json"
native_land_json <- readLines(url) %>% paste(collapse = "\n")

# 初始化地图并加载Native Land领土数据
m <- leaflet() %>% 
  addProviderTiles("Esri.WorldImagery") %>% 
  addGeoJSON(
    native_land_json, 
    fillColor = "#f39c12", 
    fillOpacity = 0.3, 
    color = "#2c3e50", 
    weight = 1,
    popup = ~paste("<strong>族群:</strong>", properties.Name)
  )

# 添加自定义标记点
custom_marker <- data.frame(
  lng = -123.1193, 
  lat = 49.2827,
  name = "温哥华"
)
m <- m %>% addMarkers(
  data = custom_marker, 
  lng = ~lng, 
  lat = ~lat, 
  popup = ~paste("自定义地点:", name)
)

# 添加自定义多边形区域
custom_poly <- list(
  type = "Feature",
  geometry = list(
    type = "Polygon",
    coordinates = list(
      list(
        c(-123.1, 49.25),
        c(-123.05, 49.25),
        c(-123.05, 49.3),
        c(-123.1, 49.3),
        c(-123.1, 49.25)
      )
    )
  ),
  properties = list(name = "自定义研究区域")
) %>% toJSON(auto_unbox = TRUE)

# 加载自定义多边形到地图
m %>% addGeoJSON(
  custom_poly, 
  fillColor = "#2ecc71", 
  fillOpacity = 0.4,
  popup = ~properties.name
)

方案3:使用Native Land官方API获取规范数据

如果不想手动处理格式问题,可以调用Native Land的API接口获取结构化数据,接口会返回格式合规的几何信息(需遵守API调用限制)。


内容的提问来源于stack exchange,提问作者J Lal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 23:20:19