0

I want to update a certain field with the current area. What I have tried:

updated_area = iface.addVectorLayer(xx.shp, "", "ogr")
selected_feature = updated_area.selectedFeatures()
updated_area.startEditing()
for feature in selected_feature:
 feature["area"] = "$area"
 updated_area.updateFeature(feature)
updated_area.commitChanges()

I'm not getting any errors, but nor is it updating any fields.

asked Jan 23, 2023 at 14:59
4
  • 1
    Do you need the python approach ? If not, you can create a virtual field from the field calculator, defined as $area. Otherwise if you want pyqgis to do the evaluation, your feature["area"] field should be something like 'feature.geometry().area()" Commented Jan 23, 2023 at 15:43
  • Yes, unfortunately I do. It's a part of a bigger script. Commented Jan 23, 2023 at 16:57
  • does your shapefile have the area attribute already ? or does it need to be created by the script ? Commented Jan 23, 2023 at 17:03
  • There is a field called area already, but because of some clipping in the script, it needs an update. I wouldn't mind deleting it and adding a new instead, any work-around would do. Commented Jan 23, 2023 at 18:36

1 Answer 1

1

I've found a way to update the ares, but for what ever reason the numbers are whacked. Like in an unidentified unit.

updated_area = iface.addVectorLayer(xx.shp, "", "ogr")
 
area_idx = updated_area.fields().lookupField('area')
for f in updated_area.getFeatures():
 area = f.geometry().area()*626336.7007
 updated_area.dataProvider().changeAttributeValues({f.id(): {area_idx: area}})

By multiplying it with 626336.7007 I'm getting the correct numbers, however, but I would like to skip this work around.

Kadir Şahbaz
78.6k57 gold badges260 silver badges407 bronze badges
answered Jan 24, 2023 at 7:50
8
  • You haven't told us the CRS of your layer and what is the unit you are expecting. Commented Jan 24, 2023 at 8:43
  • I'm not sure how to do that. =/ Commented Jan 24, 2023 at 9:10
  • Go in your vector layer properties, the first tab, you have a section "Coordinate Reference System (CRS)". Please edit your question with these info. Commented Jan 24, 2023 at 9:47
  • If you don't know how to retrieve the CRS of the current layer using QGIS desktop, it seems you have a few more things to know in GIS and QGIS in general before diving into PyQGIS Commented Jan 24, 2023 at 9:49
  • I meant, I don't know how to do that in code. Using the GUI is not an option. Commented Jan 24, 2023 at 10:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.