I have a WardBoundary.shp
file in my project. I need to find the area of each polygon ( representing different wards).With the help of this comment on Adding Area column in Polygon layer using PyQGIS?, I executed the code. I didn't get any error but still my attribute table doesn't show area value for any ward. Only the column Area
is added in the field list. Here is the link of my shape file
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:/Users/Prachi/Desktop/Qgis sample data\Ward_Saphale_updated.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})
$area
in the field calculator not suit your needs?