Book Image

QGIS Python Programming Cookbook

Book Image

QGIS Python Programming Cookbook

Overview of this book

Table of Contents (16 chapters)
QGIS Python Programming Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Calculating the area of a polygon


This recipe simply measures the area of a polygon.

Getting ready

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.

How to do it...

Perform the following steps to measure the area of a large polygon:

  1. First, import the QGIS constants library, as follows:

    from qgis.core import QGis
    
  2. Load the layer:

    lyr = QgsVectorLayer("/qgis_data/ms/mississippi.shp", "Mississippi", "ogr")
    
  3. Access the layer's features:

    fts = lyr.getFeatures()
    
  4. Get the boundary feature:

    boundary = fts.next()
    
  5. Create the measurement object instance:

    d = QgsDistanceArea()
    
  6. Pass the polygon list to the measureArea() method:

    m = d.measurePolygon(boundary.geometry().asPolygon()[0])
    
  7. Convert the measurement from decimal degrees to miles:

    d.convertMeasurement(m, QGis.Degrees, QGis.NauticalMiles, True) 
    
  8. Verify that your...