Skip to content

Instantly share code, notes, and snippets.

@filipkral
Last active May 17, 2021 15:21
Show Gist options
  • Save filipkral/5c8e89117df7a7ed983c to your computer and use it in GitHub Desktop.
Save filipkral/5c8e89117df7a7ed983c to your computer and use it in GitHub Desktop.
Convert between geojson and sp spatial objects in R
# Convert between geojson and sp spatial objects in R
require(rgdal)
# https://stat.duke.edu/~cr173/Sta523_Fa14/spatial_data.html
s <- '{ "type": "MultiPolygon", "coordinates": [
[ [[40, 40], [20, 45], [45, 30], [40, 40]] ],
[ [[20, 35], [10, 30], [10, 10], [30, 5], [45, 20], [20, 35]],
[[30, 20], [20, 15], [20, 25], [30, 20]]
]
]}'
spatialPolygon <- readOGR(s, "OGRGeoJSON", verbose = F, p4s = '+init=epsg:4326')
#plot(spatialPolygon, axes=TRUE)
spToGeoJSON <- function(x){
# Return sp spatial object as geojson by writing a temporary file.
# It seems the only way to convert sp objects to geojson is
# to write a file with OGCGeoJSON driver and read the file back in.
# The R process must be allowed to write and delete temporoary files.
#tf<-tempfile('tmp',fileext = '.geojson')
tf<-tempfile()
writeOGR(x, tf,layer = "geojson", driver = "GeoJSON")
js <- paste(readLines(tf), collapse=" ")
file.remove(tf)
return(js)
}
js <- spToGeoJSON(spatialPolygon)
readOGR(js, "OGRGeoJSON", verbose = F, p4s = '+init=epsg:4326')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment