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?

closed as off-topic by underdark Nov 30 '16 at 19:36

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions seeking help to debug/write/improve code must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Providing a clear problem statement and evidence of a code attempt will help others to help you. See: How to create a Minimal, Complete, and Verifiable example." – underdark
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 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.

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