无法在geojson / json文件中读入R以在地图上绘图

时间:2016-02-14 12:40:57

标签: 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

欢迎任何帮助!

1 个答案:

答案 0 :(得分:4)

这是一种方式

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确实需要特定的格式。例如,http://geojsonlint.com/上的geojson字符串很好,但需要调整它们才能与leaflet一起使用。另外,至少有一个字符串格式错误,所以我添加了一个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