2

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)'Does not help

enter image description here

3

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)
  • My layer is in the coordinate system WGS 84 – Георгий Викулов Jan 30 '18 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 – Hicham Zouarhi Jan 30 '18 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 '18 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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