I'm trying to compute the areas of the new layer I created by intersecting two layers.
How can I write a script that does something equivalent to clicking Export/Add geometry columns?
I'm trying to compute the areas of the new layer I created by intersecting two layers.
How can I write a script that does something equivalent to clicking Export/Add geometry columns?
Try this code:
layer = iface.activeLayer()
provider = layer.dataProvider()
areas = [ feat.geometry().area()
for feat in layer.getFeatures() ]
field = QgsField("area", QVariant.Double)
provider.addAttributes([field])
layer.updateFields()
idx = layer.fieldNameIndex('area')
for area in areas:
new_values = {idx : float(area)}
provider.changeAttributeValues({areas.index(area):new_values})
It works for me. I tried it out in this situation:
The field 'area' was added after running the code at the Python Console of QGIS.