Skip to content

Instantly share code, notes, and snippets.

@sckott
Created March 13, 2015 23:17
Show Gist options
  • Save sckott/08de710da349e48ede3e to your computer and use it in GitHub Desktop.
Save sckott/08de710da349e48ede3e to your computer and use it in GitHub Desktop.

Playing with adding + operator for easily joining geojson objects together into a single valid geojson object. This is relatively easy with lists, but not so easy with json unless you speak json.

Get lawn package too for viewing data

devtools::install_github("ropensci/geojsonio")
devtools::install_github("ropensci/lawn")
library("geojsonio")
library("lawn")

The most recent version of geojsonio has a new function + that works with any number of geo_list objects, or json objects.

geo_list

Objects of geo_list class are returned from geojsonio::geojson_list()

a <- geojson_list(list(c(-99.74,32.45), c(-99.74,36.45)))
vecs <- list(c(-100.0,40.0), c(-101.0,40.0), c(-101.0,45.0), c(-100.0,45.0), c(-100.0,40.0))
b <- geojson_list(vecs, geometry="polygon")
a + b
#> $type
#> [1] "FeatureCollection"
#> 
#> $features
#> $features[[1]]
#> $features[[1]]$type
#> [1] "Feature"
#> 
#> $features[[1]]$geometry
#> $features[[1]]$geometry$type
...
a %>% view

b %>% view

(a + b) %>% view

json

Objects of json class are returned from geojsonio::geojson_json(). Here, add together a point and a polygon into a single FeatureCollection. Note how each started off as a FeatureCollection itself.

c <- geojson_json(list(c(-99.74,32.45), c(-99.74,36.45)))
vecs <- list(c(-100.0,40.0), c(-101.0,40.0), c(-101.0,45.0), c(-100.0,45.0), c(-100.0,40.0))
d <- geojson_json(vecs, geometry="polygon")
c + d
#> {"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[-99.74,32.45]},"properties":[]},{"type":"Feature","geometry":{"type":"Point","coordinates":[-99.74,36.45]},"properties":[]},{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[-100,40],[-101,40],[-101,45],[-100,45],[-100,40]]]},"properties":[]}]}

or pretty print

library("jsonlite")
(c + d) %>% prettify
#> {
#>     "type": "FeatureCollection",
#>     "features": [
#>         {
#>             "type": "Feature",
#>             "geometry": {
#>                 "type": "Point",
#>                 "coordinates": [
#>                     -99.74,
#>                     32.45
...

more

I plan on adding in support for adding geo_list and json together soon. And maybe others, who knows, e.g.

SpatialPointsDataFrame(...) + geojson_json(...) + geojson_list(...)
@sckott
Copy link
Author

sckott commented Mar 14, 2015

😃

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