如何在 R for Leaflet 中使用 addGeoJSON() 功能?

How do I use the addGeoJSON() feature in R for Leaflet?

谁能解释一下 addGeoJSON() 功能在 R 中是如何工作的,我无法理解文档。

?addGeoJSON => (map, geojson, layerId = NULL)

什么是 geojson 和 layerId?

我能够使用 GDAL 导入我的 GeoJSON: a1 <- readOGR(dsn = "myData.geojson", layer = "OGRGeoJSON")

如何访问列以使用 leaflet addGeoJSON() 绘制 x、y?

谢谢

addGeoJSON 的第一个参数是通过调用 leaflet() 创建的传单对象。例如,

url <- "https://raw.githubusercontent.com/glynnbird/usstatesgeojson/master/california.geojson"
geojson <- jsonlite::fromJSON(url)
library("leaflet")
leaflet() %>% 
  addTiles() %>%
  setView(lng = -98.583, lat = 39.833, zoom = 3) %>% 
  addGeoJSON(geojson)

您只需将通过 readOGR 读取的 geojson 替换为我创建的 geojson 对象

readOGR()

library("leaflet")
library("rgdal")

url <- "https://raw.githubusercontent.com/glynnbird/usstatesgeojson/master/california.geojson"
res <- readOGR(dsn = url, layer = "OGRGeoJSON")
leaflet() %>% 
  addTiles() %>%
  setView(lng = -98.583, lat = 39.833, zoom = 3) %>% 
  addPolygons(data = res)

您应该将 addPolygons(data = res) 替换为 addPolygons(data = res, lng = "feature.properties.long", lat = "feature.properties.lat")

应该适用于您上面的示例。两者都可能返回 SpatialPolygonsDataFrame class,您需要将其传递给 leaflet()addPolygons() 中的 data 参数。

好的,如果您正在从磁盘读取带有点的 geojson 文件,那么例如

geojson <- '{
  "type": "FeatureCollection",
  "features" :
  [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [ -123, 49 ]
      }, 
      "properties": {
        "a_property": "foo", 
        "some_object": {
          "a_property": 1, 
          "another_property": 2 
        }
      }
    }
  ]
}'
writeLines(geojson, "file.geojson")
res <- readOGR(dsn = "file.geojson", layer = "OGRGeoJSON")
leaflet() %>% 
  addTiles() %>%
  setView(lng = -123, lat = 49, zoom = 6) %>% 
  addMarkers(data = res)