8
QgsVectorFileWriter.writeAsVectorFormat(poly_lyr, f'{path}\\tryfile', 'utf-8', QgsCoordinateReferenceSystem('EPSG:4326'), 'GeoJSON', layerOptions=['COORDINATE_PRECISION=8'], onlySelected=True)
QgsVectorFileWriter.writeAsVectorFormat(line_lyr, f'{path}\\tryfile', 'utf-8', QgsCoordinateReferenceSystem('EPSG:4326'), 'GeoJSON', layerOptions=['COORDINATE_PRECISION=8'])

I am using these two lines respectively but it makes overwrite. I'd like to append the second layer too to the tryfile.geojson after the first one. Is that possible and what is the easiest way?

4
  • 1
    GeoJSON does not support several layers. You must write a separate GeoJSON file for each layer.
    – user30184
    Mar 26 at 19:02
  • GeoJSON doesn't support multiple layers, but support different kinds of geometry. If all attributes are the same in both layers, a solution may exist. Mar 26 at 19:36
  • Not sure about this. Because, we are able to do this in manual approach, as; right click a layer -> export -> choose a exist geojson -> save and click append layer in this dialog -> linkpicture.com/q/Capture2_35.png Mar 26 at 19:42
  • @KadirŞahbaz and yes, in my case, I have two geometries for those two layers Mar 26 at 19:45

1 Answer 1

12

You need to tell the code what to do when it encounters the same file. For this, you need to use for the second export:

options = QgsVectorFileWriter.SaveVectorOptions()
options.actionOnExistingFile = QgsVectorFileWriter.AppendToLayerNoNewFields
file_path = "path/to/file.geojson"

....

# Options for the second layer
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = 'GeoJSON'
options.fileEncoding = 'utf-8'
options.layerOptions = ['COORDINATE_PRECISION=8']
# action on existing geojson
options.actionOnExistingFile = QgsVectorFileWriter.AppendToLayerNoNewFields

# Append the line layer
QgsVectorFileWriter.writeAsVectorFormat(line_lyr, file_path, options)
0

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.