2

When I run a script to calculate an area with PyQGIS I don't get the same result as when I calculate it with the Expression Builder.

Here is my script:

myLayer.startEditing()
myIndex = myLayer.fields().indexFromName("pyqgis")
for feature in myLayer.getFeatures():
    myLayer.changeAttributeValue(feature.id(), myIndex, round(feature.geometry().area()/10000, 4))        
myLayer.commitChanges()

Here is my expression :

 $area /10000

Both fields are in the same type and have the same precision Fields

But result isn't the same.

values

I'm uing QGIS 3.10.2 (LTR)

extent

2
  • 1
    Which CRS is your layer in? Which extent do your features have?
    – Erik
    Commented Oct 20, 2020 at 8:33
  • This layer is in EPSG 2154 (RGF93 / Lambert-93). Extent is defined in provider but not in spatial extent. I have updated my post with a screenshot.
    – GeoGyro
    Commented Oct 20, 2020 at 8:38

1 Answer 1

2

First, make sure you use a projected CRS

There are 2 ways to calculate the area using the field calculator.

  1. using area which is always planimetric in the SRS of this geometry. From QGIS help:

This differs from the calculations performed by the $area function, which will perform ellipsoidal calculations based on the project's ellipsoid and area unit settings.

  1. using $area

Change your expression to: area($geometry)/10000 (Edit: @Erik)

2
  • 3
    It should be area($geometry)/10000. Otherwise the expression wont work.
    – Erik
    Commented Oct 20, 2020 at 8:42
  • Great, i didn't know this (although it's written in help section, shame on me). This work great, thanks.
    – GeoGyro
    Commented Oct 20, 2020 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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