Trouble reading in geojson/json file into R for plotting on map

半腔热情 提交于 2020-01-23 11:35:48

问题


I'm trying to read in a json file which contains polylines into R for plotting in leaflet or ggmap. The file is in the geojson format.

The file can be found at: http://datasets.antwerpen.be/v4/gis/statistischesector.json

I've tried:

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

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

This actually reads in the file but it seems to be in a wrong format for further processing.

Alternatively:

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

Returns:

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

Any help is welcome!


回答1:


Here's one way

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)

leaflet::addGeoJSON does indeed want a particular format. E.g., the geojson strings are fine on http://geojsonlint.com/ but they need to be tweaked to work with leaflet. also, there was at least one string that was malformed, so i added a tryCatch to skip those

all polygons

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)



来源:https://stackoverflow.com/questions/35391869/trouble-reading-in-geojson-json-file-into-r-for-plotting-on-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!