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

Daz*_*zle 5 r geojson leaflet

有人可以解释一下addGeoJSON()功能在R中是如何工作的,我无法理解文档.

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

什么是geojson和layerId?

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

如何使用传单addGeoJSON()访问列以绘制x,y?

谢谢

sck*_*ott 6

第一个参数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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你可以readOGRgeojson我创建的对象替换你的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)
Run Code Online (Sandbox Code Playgroud)

此时应更换addPolygons(data = res)addPolygons(data = res, lng = "feature.properties.long", lat = "feature.properties.lat")

应该适用于上面的例子.两者都可能返回一个SpatialPolygonsDataFrame类,您需要将其传递给或者data参数.leaflet()addPolygons()

好的,如果您正在从磁盘读取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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述