Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. from qgis.core import QgsVectorLayer,QgsVectorDataProvider
  4. from qgis.PyQt.QtCore import QVariant
  5.  
  6. # ****Choose**** where you want to calculate your area
  7.  
  8. # from a layer stored somewhere in your computer
  9. layer = QgsVectorLayer('C:/Users/Prachi/Desktop/Qgis sample dataWard_Saphale_updated.shp', 'WardBoundary', 'ogr')
  10.  
  11. # in the active layer in the TreeLayer (the undelying layer)
  12. #layer = iface.activeLayer()
  13.  
  14. # Here we get the capabilities of your layer (Add attribute layer, edit feature ect ..
  15. caps = layer.dataProvider().capabilities()
  16.  
  17. # We make a list of fields from their name
  18. fields_name = [f.name() for f in layer.fields()]
  19.  
  20. # We check if we can add an attribute to the layer.
  21. if caps & QgsVectorDataProvider.AddAttributes:
  22. # We check if the attribute field is not exist
  23. if "Area" not in fields_name:
  24. # We add the field name Area and with the double type (it can be integer or text
  25. layer.dataProvider().addAttributes([QgsField("Area", QVariant.Double)])
  26. # We update layer's field otherwise we'll not have the field
  27. layer.updateFields()
  28. # Recreate the list field by the name to have index of the field
  29. fields_name = [f.name() for f in layer.fields()]
  30. # we get the index of the Area field
  31. fareaidx = fields_name.index('Area')
  32. else:
  33. # We are here because there is a field name Area
  34. print("The Area field is already added")
  35. # Recreate the list field by the name to have index of the field
  36. fields_name = [f.name() for f in layer.fields()]
  37. # we get the index of the Area field
  38. fareaidx = fields_name.index('Area')
  39.  
  40. # Here we check if we can change attribute of the layer
  41. if caps & QgsVectorDataProvider.ChangeAttributeValues:
  42. # we loop^on every feature
  43. for feature in layer.getFeatures():
  44. # For each feature :
  45. # We calculate the area and put the index of the field Area
  46. # We round the area value by 2 digit
  47. attrs = {fareaidx : round(feature.geometry().area(), 2)}
  48. # We change the the value of Area Field for this feature.
  49. layer.dataProvider().changeAttributeValues({feature.id() : attrs})
  50.  
  51. layer = QgsVectorLayer("C:/Users/Prachi/Desktop/Qgis sample dataWard_Saphale_updated.shp", "WardBoundary", "ogr")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement