【问题标题】:How do I use the addGeoJSON() feature in R for Leaflet?如何在 R for Leaflet 中使用 addGeoJSON() 功能?
【发布时间】:2015-08-03 23:29:00
【问题描述】:

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

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

什么是geojson和layerId?

我能够使用 GDAL 导入我的 GeoJSON: a1

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

谢谢

【问题讨论】:

    标签: r leaflet geojson


    【解决方案1】:

    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 类,您需要将其传递给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)
    

    【讨论】:

    • 亲爱的 Scott,如果我添加自己的 GeoJSON 文件,则不会发生任何事情。作为数据框,我需要的列是 lat / long,作为 geojson 对象,它们是 feature.properties.lat & long。知道如何通过 R 将这些点添加到我的传单地图中吗?谢谢
    • 我将编辑上面的答案以使用readOGR(),等一下,刷新页面
    • 还是不行,我在找积分,addMarkers 也不行。知道如何使用 AddGeoJSON() 添加点吗?
    • 我不认为你想要 addGeoJSON() - 只有当你有 geojson 数据要传入时。readOGR 应该将你读入的 geojson 转换为空间类对象。当你做class(a1)时你会得到什么
    • 它是一个 SpatialPointsDataFrame,从原来的 .GeoJSON 格式转换而来。我可以使用 Javascript + Leaflet 通过 HTML 在我的浏览器中加载 GeoJSON 文件,但使用 R + Leaflet 显示点还没有运气
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    相关资源
    最近更新 更多