2

I'm exporting xml-data files to geopackage, which seems to work. However, the coordinate reference system is not included in the xml-data, but I know it is EPSG:25832. How can I set the CRS system when writing the layer to file with the QGSVectorFileWriter?

My code looks like this. :

dlayer = QgsVectorLayer(filename, 'layer_name', 'ogr')
writer = QgsVectorFileWriter.writeAsVectorFormat(dlayer, outputFilename, "utf-8", dlayer.crs() , "GPKG")

Here I use the CRS from the XML-file, which doesn't have one . How can I set the CRS to EPSG:25832 ? I did try already to include the crs as string, but this didn't work and I created a QgsReferenceObject, but his didn't throw any errors but it didn't set the CRS.

7
  • 2
    Seems like QgsVectorFileWriter has no method do define a CRS, but you can simply use .setCrs() before for QgsVectorLayer's. See gis.stackexchange.com/questions/136378/… for example.
    – MrXsquared
    Commented Dec 20, 2023 at 12:42
  • Oh boy, you don't know how much this helped me! Thank you @MrXsquared
    – i.i.k.
    Commented Dec 20, 2023 at 12:49
  • @Taras I did try your solution beforehand, and unfortunately it didn't work for my data. However, I think I specified the CRS with lower cases (so:epsg:25832). Maybe this matters.
    – i.i.k.
    Commented Dec 20, 2023 at 14:01
  • It is True. I think it really may have sth to do with the structure of the data (it is xml).
    – i.i.k.
    Commented Dec 20, 2023 at 14:08
  • 3
    The destCRS parameter is use to reproject the data from current crs. I guess your problem is that your source layer (your xml loaded in a QgsVectorLayer) does not have any crs associated. QGIS seems to consider your layer as valid but I'm pretty sure it's not. Consequently, QGIS is not able to reproject from nothing to EPSG:25832 This also explain that the solution you found (setting the crs on the layer) works. Then you say to QGIS reproject my EPSG:25832 layer to EPSG:25832 which basically does nothing.
    – YoLecomte
    Commented Dec 20, 2023 at 15:05

1 Answer 1

3

This answer is actually from the comment of @MrXsquared.

The solution was, to first correct the CRS of the input layer, and then take that CRS as input for the QGsVectorFileWriter. The code:

# create QgsVectorLayer -object            
dlayer = QgsVectorLayer(filename, 'layer_name', 'ogr')

# Set the CRS for the object 
crs = dlayer.crs()
crs.createFromId(25832)
dlayer.setCrs(crs)

# Then take the CRS as input for the export
QgsVectorFileWriter.writeAsVectorFormat(dlayer, outputFilename, "utf-8", dlayer.crs(), "GPKG")


Your Answer

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

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