如何在R中使用addGeoJSON()功能来制作Leaflet地图?

5

请问有人能解释一下R语言中的addGeoJSON()功能是如何工作的吗?我看不懂文档。

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

geojson和layerId是什么意思?

我已经通过GDAL导入了我的GeoJSON文件:

a1 <- readOGR(dsn = "myData.geojson", layer = "OGRGeoJSON")

我该如何使用leaflet的addGeoJSON()函数访问列以绘制x,y坐标?

谢谢

1个回答

9
addGeoJSON的第一个参数是从调用leaflet()创建的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

你可以用我创建的geojson对象替换通过readOGR读入的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, lng = "feature.properties.long", lat = "feature.properties.lat")替换addPolygons(data = res)

对于你上面的例子应该有效。两者都可能返回一个SpatialPolygonsDataFrame类,你需要将其传递给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)

enter image description here


亲爱的Scott, 如果我添加自己的GeoJSON文件,什么也不会发生。作为数据框,我需要的列是lat / long,而作为geojson对象,它们是feature.properties.lat和long。您有任何想法如何通过R将这些点添加到我的leaflet地图中吗?谢谢 - Dazzle
我会编辑上面的答案,使用readOGR(),稍等一下,刷新页面。 - sckott
还是不行,我正在寻找解决方法,addMarkers也不起作用。你有什么办法可以使用AddGeoJSON()添加点吗? - Dazzle
我认为你不需要使用addGeoJSON()函数 - 只有当你有geojson数据需要传递时才需要使用。readOGR函数应该将你读取的geojson转换为空间类对象。当你执行class(a1)时,你会得到什么? - sckott
这是一个SpatialPointsDataFrame,它是从原始的.GeoJSON格式转换而来。我能够使用Javascript + Leaflet在我的浏览器中加载GeoJSON文件,但是在R + Leaflet中尚未成功显示点。 - Dazzle
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接