3

If you use the field calculator in Qgis considers the area in square meters, and when using the script gives the area in degrees. My layer is in the coordinate system WGS 84

vlayer=r"K:/temp/gpp_utm.shp"
vlayer.startEditing()
myField=QgsField('myattr',QVariant.Double)
vlayer.dataProvider().addAttributes([myField])
vlayer.updateFields()
idx=vlayer.fieldNameIndex('myattr')
# vlayer.addAttribute(myField)
# idx=vlayer.fieldNameIndex('myattr')
e=QgsExpression('$area')
e.prepare(vlayer.pendingFields())
for f in vlayer.getFeatures():
    f[idx]=e.evaluate(f)
    vlayer.updateFeature(f)
vlayer.commitChanges()

How to calculate the area in meters and not in degree in my script? I tried to put $area(m2) but it did not help.

enter image description here

2

1 Answer 1

4

the area is computed in degrees because the CRS of your layer in the script isn't provided so it goes for the default one ( EPSG: 4326 )

to set the crs for your layer in pyqgis, you can add these lines

crs.createFromId(3857) # for the pseudo mercator, or choose any other projection you want
vlayer.setCrs(crs)
4
  • My layer is in the coordinate system WGS 84 Jan 30, 2018 at 8:58
  • 2
    @ГеоргийВикулов yes and that's why you get your area in degrees, since the unit for WGS 84 is degrees, you have to change the CRS to a projected system, the universal one would be EPSG: 3857 Jan 30, 2018 at 9:00
  • i added crs=vlayer.crs() crs.createFromId(3857) vlayer.setCrs(crs) But he also thinks in degrees although the projection changed Jan 30, 2018 at 9:38
  • Web Mercator should not be used for area calculations, since it is known to be highly inaccurate for the purpose. I wouldn't use it for measuring a small equatorial island, much less a large polar region.
    – Vince
    Feb 7, 2020 at 20:50

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.