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.

i.i.k.
  • 1,427
  • 5
  • 11
  • 2
    Seems like QgsVectorFileWriter has no method do define a CRS, but you can simply use .setCrs() before for QgsVectorLayer's. See https://gis.stackexchange.com/questions/136378/defining-layer-crs-and-avoiding-crs-dialog-in-pyqgis for example. – MrXsquared Dec 20 '23 at 12:42
  • Oh boy, you don't know how much this helped me! Thank you @MrXsquared – i.i.k. Dec 20 '23 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. Dec 20 '23 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. Dec 20 '23 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 Dec 20 '23 at 15:05
  • @YoLecomte That sounds very valid! Thanks for the explanation! In QGIS it also didn't have a valid CRS, I had to set it manually. – i.i.k. Dec 20 '23 at 15:25
  • @i.i.k. yes that make sense. – YoLecomte Dec 20 '23 at 15:48

1 Answers1

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")

i.i.k.
  • 1,427
  • 5
  • 11