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)
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
klaus k.
  • 113
  • 5

0 Answers0