1

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.

2
  • Is it possible that you share your KML with us ?
    – Taras
    Commented Nov 8, 2022 at 17:55
  • 1
    Unfortunately not since it has some geographic data that I'm not at liberty to share, but the goal is that I can open the file in google earth and the numbers will be in order. I will update the question with a screenshot from google earth with what they look like now.
    – tbob
    Commented Nov 8, 2022 at 18:05

1 Answer 1

1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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