I'm new to QGIS AND Python.
This is how I'm trying to calculate all areas of the layer named polygons:
def add_area():
layers = QgsMapLayerRegistry.instance().mapLayers().values()
foundlayer = False
for layer in layers:
if layer.name() == 'polygons':
inputlayer = QgsMapLayerRegistry.instance().mapLayersByName("polygons")[0]
print ('polygons-layer found')
iface.setActiveLayer(inputlayer)
foundlayer = True
if not foundlayer:
print ("polygons does not exist")
#maybe not the most elegant way, but it works till here as it should :-)
area = 0
#this creates me a new column named "Area"
provider = inputlayer.dataProvider()
provider.addAttributes([QgsField("Area",QVariant.Double)])
#and now I'm iterating through all features to calculate each polygons area...
features = inputlayer.getFeatures()
f = features.next()
for f in features:
attribute = (f.attributes())
print(attribute)
calculator = QgsDistanceArea()
area = calculator.measurePolygon(f.geometry(). asPolygon()[0])
calculator.convertMeasurement(area, QGis.Degrees, QGis.Meters, True)
inputlayer.updateFields()
Even it creates the new column in the attribute table, I'm getting this Error:
Layer polygons: SQLite error: duplicate column name: Area SQL: ALTER TABLE "polygons" ADD COLUMN "Area"
tried to google it but couldn't find a answer in any forum, that I understand and that help's me solving it.
Do I get the message, because the column "Area" is already created? (that is possible, because I naturally tried my code several times! But I got this message already the first time...!?)