【问题标题】:Trouble reading in geojson/json file into R for plotting on map将 geojson/json 文件读入 R 以在地图上绘图时遇到问题
【发布时间】:2016-02-14 12:40:57
【问题描述】:

我正在尝试将包含折线的 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

欢迎任何帮助!

【问题讨论】:

  • 你能证明路径是正确的吗?
  • 为了便于阅读,我缩短了示例中的路径。当我这样做时: path
  • 我猜我必须在使用 readLines 函数读取文件后对文件进行某种转换..
  • 我认为这是错误的,因为我无法使用传单绘制折线。 Leaflet() %>% setView(lng = 4.401, lat = 51.21, zoom = 10) %>% addTiles() %>% addGeoJSON(geojson)
  • 你的意思是你得到了世界地图,但什么都没有?

标签: json r leaflet geojson ggmap


【解决方案1】:

这是一种方法

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/ 上很好,但需要对其进行调整以与 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)

【讨论】:

  • 谢谢斯科特!是否可以一次绘制所有折线?我注意到您可以通过在“geoms”之后立即增加索引来在当前代码中绘制不同的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多