This recipe simply measures the area of a polygon.
For this recipe, we'll use a single-feature polygon shapefile, which you can download from https://geospatialpython.googlecode.com/files/Mississippi.zip
Unzip the shapefile and put it in a directory named qgis_data/ms within your root or home directory.
Perform the following steps to measure the area of a large polygon:
from qgis.core import QGis
lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
fts = lyr.getFeatures()
boundary = fts.next()
d = QgsDistanceArea()
measureArea()
method:m = d.measurePolygon(boundary.geometry().asPolygon()[0])
d.convertMeasurement(m, QGis.Degrees, QGis.NauticalMiles, True)
(42955.47889640281, 7)
PyQIS has no measureArea()
method, but it has a
measurePolygon()
method in the QgsDistanceArea
object. The method accepts a list of points. In this case, when we convert the measurement output from decimal degrees to miles, we also specify True
in the convertMeasurement()
method so that QGIS knows that it is an area calculation. Note that when we get the boundary geometry as a polygon, we use an index of 0, suggesting that there is more than one polygon. A polygon geometry can have inner rings, which are specified as additional polygons. The outermost ring, in this case the only ring, is the first polygon.