2

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?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
casta2k
  • 155
  • 2
  • 8
  • 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

1 Answers1

6

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.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
xunilk
  • 29,891
  • 4
  • 41
  • 80