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
-
1Do 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()"Kasper– Kasper2023年01月23日 15:43:27 +00:00Commented Jan 23, 2023 at 15:43
-
Yes, unfortunately I do. It's a part of a bigger script.Tobias Bowley– Tobias Bowley2023年01月23日 16:57:04 +00:00Commented Jan 23, 2023 at 16:57
-
does your shapefile have the area attribute already ? or does it need to be created by the script ?Kasper– Kasper2023年01月23日 17:03:27 +00:00Commented 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.Tobias Bowley– Tobias Bowley2023年01月23日 18:36:28 +00:00Commented Jan 23, 2023 at 18:36
1 Answer 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
-
You haven't told us the CRS of your layer and what is the unit you are expecting.etrimaille– etrimaille2023年01月24日 08:43:08 +00:00Commented Jan 24, 2023 at 8:43
-
I'm not sure how to do that. =/Tobias Bowley– Tobias Bowley2023年01月24日 09:10:57 +00:00Commented 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.etrimaille– etrimaille2023年01月24日 09:47:08 +00:00Commented 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 PyQGISetrimaille– etrimaille2023年01月24日 09:49:26 +00:00Commented 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.Tobias Bowley– Tobias Bowley2023年01月24日 10:14:18 +00:00Commented Jan 24, 2023 at 10:14
lang-py