TransWikia.com

Defining KML Name element when using QgsVectorFileWriter

Geographic Information Systems Asked by nmokht97 on February 12, 2021

I am trying to use QgsVectorFileWriter to write a kml file from a Shape file.
I would like to define the KML Name (called NameField in the QGIS save-as GUI) to correspond with a field in my shapefile, which is called "NAME".

The solution given in How to define KML Name element when using QgsVectorFileWriter? doesn’t work for me.

Below is my code

from qgis.core import QgsVectorFileWriter, QgsVectorLayer

data_source = r"C:Users....PT.shp"
layer = QgsVectorLayer(data_source, "layer_name", "ogr")
output_layer = r"C:Users....PT_test"
QgsVectorFileWriter.writeAsVectorFormat(layer, output_layer, "utf-8",layer.crs(),"KML",datasourceOptions = "NAME")

print ("Layer to KML Conversion Complete")
print (output_layer + " is now a .kml")   

One Answer

It needs to be a list:

    name = "NAME"
    datasource_options = []
    datasource_options += ["DescriptionField=" + name]
    datasource_options += ["NameField=" + name]

    QgsVectorFileWriter.writeAsVectorFormat(layer, output_layer, "utf-8",layer.crs(),"KML",datasourceOptions = datasource_options)

Correct answer by John on February 12, 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