2

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())
d.setEllipsoid(QgsProject.instance().ellipsoid())
#https://gis.stackexchange.com/questions/309721/creating-and-updating-a-field-from-calculation?rq=1
#https://gis.stackexchange.com/questions/289601/how-to-fill-fields-with-layer-name-in-pyqgis
with edit(myLyr):
   fldindex = myLyr.fields().indexOf(fldname)
   if fldindex == -1:
       print("Das gesuchte Feld {} ist nicht im Layer {}!".format(fldname, myLyr.name()))
   else:
       fts = myLyr.getFeatures()
       for f in fts:
           geom = f.geometry()
           v=(d.measureArea(geom))
           #print("Fläche in qm ist {}!".format(v))
           f[fldindex]=v
           myLyr.updateFeature(f)
4
  • 2
    For review of working code there is the Code Review Stack Exchange.
    – PolyGeo
    Oct 6, 2019 at 21:53
  • 1
    Looks fine, are you having issues?
    – Joseph
    Oct 7, 2019 at 10:59
  • No there aren't issue. My hope was to make the code shorter
    – klaus k.
    Oct 7, 2019 at 19:25
  • Years later, this still helped me getting the right area (like the expression $area would). Thank you!
    – Homerun_
    Sep 21, 2023 at 9:32

0

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.