无法将geojson/json文件读入R以便在地图上绘图 [英] Trouble reading in geojson/json file into R for plotting on map

查看:376
本文介绍了无法将geojson/json文件读入R以便在地图上绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取一个json文件,该文件包含R中的折线,以便在传单或ggmap中进行绘制.该文件为geojson格式.

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.

可以在以下位置找到文件: http://datasets.antwerpen.be/v4/gis/statistischesector.json

The file can be found at: 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)

这实际上是从文件中读取的,但似乎格式错误,无法进行进一步处理.

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

或者:

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)

leaflet::addGeoJSON确实确实需要特定的格式.例如,在 http://geojsonlint.com/上使用geojson字符串就可以了,但是需要对其进行调整才能使用leaflet.另外,至少有一个格式错误的字符串,所以我添加了tryCatch来跳过这些字符串

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

所有多边形

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)

这篇关于无法将geojson/json文件读入R以便在地图上绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆