I have a WardBoundary.shp
file with Polygon Features in it. I have to calculate the area of each Polygon and write into attribute Table.
I can do manually by using '$area` but I need to automate this process using Pyqgis3.
I have seen Add area column using PyQGIS but I am unable to get area as well as code.
Answer
Here I put some lines that must be execute from the python console of Qgis. I use the Developer Cookbook of Qgis 3.
#!/usr/bin/python3
from qgis.core import QgsVectorLayer, QgsVectorDataProvider
from qgis.PyQt.QtCore import QVariant
# ****Choose**** where you want to calculate your area
# from a layer stored somewhere in your computer
layer = QgsVectorLayer('c:\temp\ward_boundary.shp', 'WardBoundary', 'ogr')
# in the active layer in the TreeLayer (the undelying layer)
#layer = iface.activeLayer()
# Here we get the capabilities of your layer (Add attribute layer, edit feature ect ..
caps = layer.dataProvider().capabilities()
# We make a list of fields from their name
fields_name = [f.name() for f in layer.fields()]
# We check if we can add an attribute to the layer.
if caps & QgsVectorDataProvider.AddAttributes:
# We check if the attribute field is not exist
if "Area" not in fields_name:
# We add the field name Area and with the double type (it can be integer or text
layer.dataProvider().addAttributes([QgsField("Area", QVariant.Double)])
# We update layer's field otherwise we'll not have the field
layer.updateFields()
# Recreate the list field by the name to have index of the field
fields_name = [f.name() for f in layer.fields()]
# we get the index of the Area field
fareaidx = fields_name.index('Area')
else:
# We are here because there is a field name Area
print("The Area field is already added")
# Recreate the list field by the name to have index of the field
fields_name = [f.name() for f in layer.fields()]
# we get the index of the Area field
fareaidx = fields_name.index('Area')
# Here we check if we can change attribute of the layer
if caps & QgsVectorDataProvider.ChangeAttributeValues:
# we loop^on every feature
for feature in layer.getFeatures():
# For each feature :
# We calculate the area and put the index of the field Area
# We round the area value by 2 digit
attrs = {fareaidx : round(feature.geometry().area(), 2)}
# We change the the value of Area Field for this feature.
layer.dataProvider().changeAttributeValues({feature.id() : attrs})
No comments:
Post a Comment