TransWikia.com

Saving shapefile layer as KML with datasourceOptions using PyQGIS

Geographic Information Systems Asked by Andrea Guardavilla on January 10, 2021

I’m trying to export a shapefile layer to KML format in QGIS , trough Python coding.

The code is:

QgsVectorFileWriter.writeAsVectorFormat(inputlayer, outputlayer, "utf-8", coord_system, "KML")

But I have to add dataSourceOption in the line, because I have to specify a "nameField".

How I can add dataSourceOption in the writeAsVectorFormat method?
I have see that dataSourceOption accept a QStringList() but I don’t understand.

2 Answers

datasourceOptions are passed as a list of OGR creation options for the format.

There are 2 ways: writeAsVectorFormatV2() and writeAsVectorFormat().

The first one is more neat in my opinion:

options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "KML"
options.fileEncoding = 'utf-8'
options.datasourceOptions = ["NameField=ulica"]

QgsVectorFileWriter.writeAsVectorFormatV2(layer=inputLayer, fileName=fileName, transformContext=QgsCoordinateTransformContext(), options=options)

Second option:

QgsVectorFileWriter.writeAsVectorFormat(layer=inputLayer,
                                            fileName=fileName,
                                            fileEncoding='utf-8',
                                            destCRS=crs,
                                            driverName="KML",
                                            datasourceOptions=["NameField=ulica"]
                                            )

PS. How I found the answer to your question:

Here is the documentation of QgsVectorFileWriter. The datasourceOptions parameter is described as a list of OGR data source creation options.

Here I looked up KML format Creation options in the GDAL/OGR documentation. Every format has its own specific creation options. If you need to specify any other options you just pass them in the list just as you would pass them if you used OGR/GDAL in command line.

Correct answer by Leon Powałka on January 10, 2021

Thank you!

I found a more poor solution:

editing the name of one of the field of shapefile to "NAME" that is the default field take by the writer of the QgsVectorFileWriter.writeAsVectorFormat.

Answered by Andrea Guardavilla on January 10, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP