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?

  • 2
    Welcome to gis.stackexchange! Please note that a good question on this site is expected to show some degree of research on your part, i.e. what you have tried and - if applicable - code so far. For more info, you can check our faq. – underdark Nov 30 '16 at 19:38

Try this code:

layer = iface.activeLayer()
provider = layer.dataProvider()

areas = [ feat.geometry().area() 
          for feat in layer.getFeatures() ]

field = QgsField("area", QVariant.Double)

idx = layer.fieldNameIndex('area')

for area in areas:
    new_values = {idx : float(area)}

It works for me. I tried it out in this situation:

enter image description here

The field 'area' was added after running the code at the Python Console of QGIS.

|improve this answer|||||

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