Compute vector layer area with python in qgis

I need to identify in QGIS the area of a Qgsvectorlayer .

Anyone have an idea how to do that in python ?

A Polygon vectorlayer is composed of many features (geometries), each with an area.

If the geometries don't overlap, you can iterate over the vector layer and sum the areas:

layer = iface.activeLayer()
areatot = 0
for elem in layer.getFeatures()
geom = elem.geometry()
areatot += geom.area()

or in one line:

aeratot = [sum(elem.geometry().area() for elem in layer.getFeatures())]

But if some geometries overlap, this result is wrong: You can then Union all the geometries and use the area of the resulting geometry: # creation of a empty geometry for unioning
geomtot = QgsGeometry.fromWkt('GEOMETRYCOLLECTION EMPTY')
# union
for elem in layer.getFeatures():
geomtot = geomtot.combine(elem.geometry())
area = geomtot.area()

For QGIS 1.8:

layer = qgis.utils.iface.activeLayer()
areatot = 0
layer.select()
for elem in layer:
geom = elem.geometry()
areatot += geom.area()

and:

geomtot = QgsGeometry.fromWkt('GEOMETRYCOLLECTION EMPTY')
layer.select()
for elem in layer:
geomtot = geomtot.combine(elem.geometry())
area = geomtot.area()
• yes this is what i am looking for – fkili mohamed Nov 1 '13 at 18:53
• oh the function getFeatures() does'nt work in qgis 1.8 – fkili mohamed Nov 1 '13 at 19:16
• Then use layer.select() and for feature in layer: – gene Nov 1 '13 at 19:36
• see for 1.8 version in the answer – gene Nov 1 '13 at 19:58

In Qgis, go to plugins > Python console