2

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.

0
0

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.

0

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.

1
  • Please approve my answer :). I spent some time looking for this and it is the correct approach to your problem – Leon Powałka Oct 22 '20 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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