QGIS – Repeating $area Function on Multiple Layers for Area Calculations

pyqgisqgis

I, I have 15 layers on which I want to do exactly the same operation add columns and calculate the area (–> $area)
I looked online and found some hints with batch processing tools, BUT I've got errors messages with the Python advanced field calculator and errors with batch processing tools… can someone helps me?

Best Answer

You can use pyqgis like this:

newfieldname = 'area'
for layer in QgsProject.instance().mapLayers().values(): #For each layer added to the map
    prov = layer.dataProvider()
    prov.addAttributes([QgsField(name=newfieldname, type=QVariant.Double)]) #Add an area field of type Double
    layer.updateFields()
    attributemap = {} #A dictionary to store feature id, new fieldindex, area
    fieldindex = layer.fields().indexFromName(newfieldname)
    for f in layer.getFeatures(): #For each feature add values to the dictionary
        attributemap[f.id()]={fieldindex:f.geometry().area()}
    prov.changeAttributeValues(attributemap) #Update all features

enter image description here

Related Question