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

``````vlayer = QgsVectorLayer("/path/to/shapefile/file.shp", "layer_name_you_like", "ogr")
``````

and to get extent, do

``````vlayer.extent().toString()
``````

`vlayer.extent()` return a qgis.core.QgsRectangle, so if you want, you can use different methods depending of you use case (see the doc for this component at http://qgis.org/api/2.0/classQgsRectangle.html)

Is it what you wanted?

• No I cannot use the extent of layer ,i want to identify sum of features,the answer of gene look useful for me but its work on qgis api 2 ,thank you for your answer ThomasG77 – fkili mohamed Nov 1 '13 at 19:35