6

The write. function allows one to export a JSON file, but it does not seem to work for a GeoJSON file.

This is the code i ran:

write(map,"Map Layer2.GeoJSON")

and this was the error produced:

Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'S4') cannot be handled by 'cat'
0

3 Answers 3

8

write is just a wrapper for cat (package base). See ?write:

Write Data to a File

Description

The data (usually a matrix) x are written to file file. If x is a two-dimensional matrix you need to transpose it to get the columns in file the same as those in the internal representation.

To write a GeoJSON file, you can use writeOGR() instead (package rgdal):

library("rgdal")
data(meuse)
coordinates(meuse) = c("x", "y")
class(meuse)
# [1] "SpatialPointsDataFrame"
writeOGR(meuse, "test_geojson", layer="meuse", driver="GeoJSON")
1
  • 1
    I'm seeing that layer is required, but isn't used (dsn is used to name the output file). Any idea why?
    – Matt
    Mar 6, 2017 at 19:55
7

Just to clarify rcs great answer and Matt's question for beginners. The dsn should be the path and full file name, layer is required but ignored. No, not sure why.

library("rgdal")
data(meuse)
coordinates(meuse) = c("x", "y")
writeOGR(meuse, dsn="path/test_geojson.GeoJSON", layer="meuse", driver="GeoJSON")
7

2021 Solution with the sf package

library(sf)
library(rgdal)
data(meuse)
meuse_sf = st_as_sf(meuse, coords = c("x", "y"), crs = 28992, agr = "constant")
st_write(meuse_sf, "meuse.geojson")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.