Search code examples
jsonrleafletgeojsonggmap

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


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!


Solution

  • 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)
    

    enter image description here

    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)
    

    enter image description here