PyQGIS – Save Features to KML in Specific Order

pyqgispyqgis-3qgis-3qgis-plugins

I have a layer with an attribute called 'label' which has numbers as text ('1', '2', etc…) I want a KML saved and have the features saved by order of int('label'). Is it possible?

Looks like from this question it is possible to sort features, but I want to save a KML and have the features saved in a particular order. right now my code for saving the KML layer looks like this:

    options = QgsVectorFileWriter.SaveVectorOptions()
    options.includeZ = True
    options.fileEncoding = "utf-8"
    options.driverName = "KML"
    options.overrideGeometryType = QgsWkbTypes.LineStringZ
    options.datasourceOptions = ['NameField=label']
    result = QgsVectorFileWriter.writeAsVectorFormatV3(
                                            layer=clone_layer,
                                            fileName=str(outputlayer),
                                            transformContext=QgsProject.instance().transformContext(),
                                            options=options)

right now in google earth the namefield will be out of order like this:
enter image description here

and I need it to be in order.

Best Answer

I solved this by making a new layer in memory and adding the sorted features to it and then saving it as a KML:

    def line_sort(item):
        return int(item['label'])
    lines = sorted(self.final_lines.getFeatures(), key=line_sort)
    clone_layer = QgsVectorLayer("Linestring?crs=epsg:4326", "lines", "memory")
    clone_layer.dataProvider().addAttributes([field for field in self.final_lines.fields()])
    clone_layer.updateFields()
    clone_layer.dataProvider().addFeatures(lines)
Related Question