Skip to content

Instantly share code, notes, and snippets.

@robsalasco
Last active October 4, 2020 20:25
Show Gist options
  • Save robsalasco/d0e5da3b5b0a39419bce35836a614529 to your computer and use it in GitHub Desktop.
Save robsalasco/d0e5da3b5b0a39419bce35836a614529 to your computer and use it in GitHub Desktop.
library(sf)
#> Linking to GEOS 3.8.1, GDAL 3.1.1, PROJ 7.1.0
library(tmap)
library(purrr)
library(jsonlite)
#> 
#> Attaching package: 'jsonlite'
#> The following object is masked from 'package:purrr':
#> 
#>     flatten
library(geojsonsf)

json = 'https://api.jsonbin.io/b/5f76362e302a837e9572642b'

extract_geom <- function(data) {
  geojson_sf(data %>% toJSON(auto_unbox = TRUE))
}

sf_list <- map(read_json(json)$response, extract_geom)

st_as_sf(data.table::rbindlist(sf_list)) %>% 
  tm_shape() + 
  tm_polygons()

# True shapes extracted from json

shp1 <- geojson_sf('{"_id":{"$oid":"5f734aca3426060a6d0a9ebd"},"type":"Feature","properties":{"id_comunas":"16106","manzana":"3762"},"geometry":{"type":"Polygon","coordinates":[[[-70.65843928154064,-33.48961317801985],[-70.65848925637721,-33.489741566369396],[-70.65881916803056,-33.489651408281304],[-70.65876919277032,-33.48952302007645],[-70.65843928154064,-33.48961317801985]]]}}')
shp2 <- geojson_sf('{"_id":{"$oid":"5f734acd3426060a6d0aa4a9"},"type":"Feature","properties":{"id_comunas":"16106","manzana":"3762"},"geometry":{"type":"Polygon","coordinates":[[[-70.65721044300078,-33.489864502691425],[-70.65716694092083,-33.489874250662815],[-70.6572020152041,-33.48998248754131],[-70.65743435449795,-33.48992965864198],[-70.6573973690393,-33.4898278349771],[-70.65721044300078,-33.489864502691425]]]}}')

st_as_sf(data.table::rbindlist(list(shp1, shp2))) %>% 
  tm_shape() + 
  tm_polygons()

Created on 2020-10-01 by the reprex package (v0.3.0)

@dcooley
Copy link

dcooley commented Oct 1, 2020

Here's how I would do it (as per my tweet )

library(sf)
library(jqr)
library(geojsonsf)

json <- 'https://api.jsonbin.io/b/5f76362e302a837e9572642b'
lns <- readLines( json )

sf <- jq( lns, ".[]") %>%     ## the .[] takes you one-level down the JSON
  geojsonsf::geojson_sf()   ## then geojsonsf can handle the geojson structure after that

# Simple feature collection with 2 features and 2 fields
# geometry type:  POLYGON
# dimension:      XY
# bbox:           xmin: -70.65882 ymin: -33.48998 xmax: -70.65717 ymax: -33.48952
# z_range:        zmin: NA zmax: NA
# m_range:        mmin: NA mmax: NA
# geographic CRS: WGS 84
# id_comunas manzana                       geometry
# 1      16106    3762 POLYGON ((-70.65844 -33.489...
# 2      16106    3762 POLYGON ((-70.65721 -33.489...

library(mapdeck)

set_token(secret::get_secret("mapbox"))

mapdeck() %>% 
  add_sf( data = sf )

Screen Shot 2020-10-02 at 7 30 45 am

@robsalasco
Copy link
Author

Thank you again @dcooley :) 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment