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

时间:2015-08-03 23:29:01

标签: r leaflet geojson

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

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

什么是geojson和layerId?

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

如何使用传单addGeoJSON()?

访问列以绘制x,y

由于

1 个答案:

答案 0 :(得分: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)

enter image description here

您可以通过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类,您需要将其传递到dataleaflet()中的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)

enter image description here