Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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:tempward_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})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement