Is this the the best solution to calculate the area of the features?

parent = iface.mainWindow()
mc = iface.mapCanvas()
fldname = "m2" #field which has the values for squaremeters
myLyr = mc.currentLayer() 
d = QgsDistanceArea()
d.setSourceCrs(myLyr.crs(), QgsProject.instance().transformContext())
with edit(myLyr):
   fldindex = myLyr.fields().indexOf(fldname)
   if fldindex == -1:
       print("Das gesuchte Feld {} ist nicht im Layer {}!".format(fldname, myLyr.name()))
       fts = myLyr.getFeatures()
       for f in fts:
           geom = f.geometry()
           #print("Fläche in qm ist {}!".format(v))
  • 2
    For review of working code there is the Code Review Stack Exchange.
    – PolyGeo
    Commented Oct 6, 2019 at 21:53
  • 1
    Looks fine, are you having issues?
    – Joseph
    Commented Oct 7, 2019 at 10:59
  • No there aren't issue. My hope was to make the code shorter
    – klaus k.
    Commented Oct 7, 2019 at 19:25
  • Years later, this still helped me getting the right area (like the expression $area would). Thank you!
    – Homerun_
    Commented Sep 21, 2023 at 9:32


Your Answer

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

Browse other questions tagged or ask your own question.