我正在尝试将包含折线的 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)
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)
关于json - 将 geojson/json 文件读入 R 以便在 map 上绘制时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35391869/