json - 将 geojson/json 文件读入 R 以便在 map 上绘制时遇到问题

标签 json r leaflet geojson ggmap

我正在尝试将包含折线的 json 文件读入 R 中,以便在传单或 ggmap 中进行绘图。文件为geojson格式。

该文件位于:http://datasets.antwerpen.be/v4/gis/statistischesector.json

我已经尝试过:

library(rgdal) 
library(jsonlite)
library(leaflet)

geojson <- readLines("statistischesector.json", warn = FALSE) %>%
  paste(collapse = "\n") %>%
  fromJSON(simplifyVector = FALSE)

这实际上读取了文件,但似乎格式错误,无法进行进一步处理。

或者:

readOGR(dsn="~/statistischesector.json", layer="OGRGeoJSON")

返回:

Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv,  : 
  Cannot open data source

欢迎任何帮助!

最佳答案

这是一种方法

library("jsonlite")
library("leaflet")
x <- jsonlite::fromJSON("http://datasets.antwerpen.be/v4/gis/statistischesector.json", FALSE)

geoms <- lapply(x$data, function(z) {
  dat <- tryCatch(jsonlite::fromJSON(z$geometry, FALSE), error = function(e) e)
  if (!inherits(dat, "error")) {
    list(type = "FeatureCollection",
         features = list(
           list(type = "Feature", properties = list(), geometry = dat)
         ))
  }
})

leaflet() %>%
  addTiles() %>%
  addGeoJSON(geojson = geoms[1]) %>%
  setView(
    lng = mean(vapply(geoms[1][[1]]$features[[1]]$geometry$coordinates[[1]], "[[", 1, 1)),
    lat = mean(vapply(geoms[1][[1]]$features[[1]]$geometry$coordinates[[1]], "[[", 1, 2)),
    zoom = 12)

enter image description here

leaflet::addGeoJSON 确实需要特定的格式。例如,geojson 字符串在 http://geojsonlint.com/ 上很好。但它们需要进行调整才能与传单一起使用。另外,至少有一个字符串格式错误,因此我添加了一个 tryCatch 来跳过这些

所有多边形

gg <- list(type = "FeatureCollection", 
           features = 
             Filter(Negate(is.null), lapply(x$data, function(z) {
               dat <- tryCatch(jsonlite::fromJSON(z$geometry, FALSE), error = function(e) e)
               if (!inherits(dat, "error")) {
                 list(type = "Feature", 
                      properties = list(), 
                      geometry = dat)
               } else {
                 NULL
               }
             }))
)

leaflet() %>% 
  addTiles() %>% 
  addGeoJSON(geojson = gg) %>% 
  setView(lng = 4.5, lat = 51.3, zoom = 10)

enter image description here

关于json - 将 geojson/json 文件读入 R 以便在 map 上绘制时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35391869/

相关文章:

javascript - 如何获取 JSON 对象中的所有键 (javascript)

javascript - 从 Javascript 文件调用 Rest API : Data Return Issue

arrays - 在循环中将变量添加到 bash 数组

r - 有没有一种简单的方法可以将预测恢复为时间序列以进行绘图?

r - 为什么这个简单的功能不起作用?

R Shiny Leaflet 标记缩放问题

javascript - 将 openPopup() 与 Leaflet.js + 集群一起使用

javascript - 传单 - openPopup() 未使用 geoJSON 显示

java - jar执行期间资源路径改变

r - 如何减少 r 中预处理配方对象的大小?