1

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
5

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:

enter image description here

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

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