TransWikia.com

Merge features before creating new shapefile in PyQGIS

Geographic Information Systems Asked on July 18, 2021

I’m working with QGIS 3.10 A Coruña on MacOS 10.13 environment.
I’ve got the following code (provided by @Kadir Şahbaz in this thread) to create new shapefiles from a loop selection of features for each different attribute value

layer = qgis.utils.iface.mapCanvas().currentLayer()

field_name = "CODNUT2"
idx = layer.fields().indexOf(field_name)
unique_values = layer.uniqueValues(idx)

folder = "/path/to/folder"

for value in unique_values:
    file_path = f"{folder}/_{value}.shp"
    layer.selectByExpression(f"{field_name}='{value}'")
    
    QgsVectorFileWriter.writeAsVectorFormat(layer,
                                            file_path,
                                            'utf-8',
                                            layer.crs(),
                                            "ESRI Shapefile",
                                            onlySelected=True
                                            )

Now I need to merge all features in each selection before creating the shapefile. I’ve tried including the following chunk of code in line 12

layer.combine(layer.selectByExpression(f"{field_name}='{value}'"))

obtaining the following error message

AttributeError: 'QgsVectorLayer' object has no attribute 'combine'

How can it be mended?

One Answer

So I solved the problem by creating a temporary layer to save combined geometry and then write it to shp. I added the attribute which you use for the selection. You can delete if you do not want to have any attribute

layer = qgis.utils.iface.mapCanvas().currentLayer()

field_name = "CODNUT2"
idx = layer.fields().indexOf(field_name)
unique_values = layer.uniqueValues(idx)

folder = "/path/to/folder"

for value in unique_values:
    file_path = f"{folder}/_{value}.shp"
    layer.selectByExpression(f"{field_name}='{value}'")
    
    geom = None
    for feat in layer.selectedFeatures():
        if geom == None:
           geom = feat.geometry()
        else:
           geom = geom.combine(feat.geometry())
        
    # Create temp layer to save the combined geom
    vl = QgsVectorLayer("Polygon?crs=epsg:25830", 
                      value, 
                      "memory")

    pr = vl.dataProvider()
    
    # Add Attr to temp layer 
    pr.addAttributes([QgsField("CODNUT2", QVariant.String)])
    vl.updateFields()

    # Add geom to temp layer 
    f = QgsFeature()
    f.setGeometry(geom)
    f.setAttributes([value])
    pr.addFeature(f)
    vl.updateExtents()

    #QgsProject.instance().addMapLayer(vl)
    
    QgsVectorFileWriter.writeAsVectorFormat(vl,
                                            file_path,
                                            'utf-8',
                                            vl.crs(),
                                            "ESRI Shapefile"
                                            )

Correct answer by Nil on July 18, 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