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

梦想与她 提交于 2019-12-06 03:09:31

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)

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