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

Measuring the distance along a line sample


In this recipe, we'll measure the distance along a line with multiple vertices.

Getting ready

For this recipe, we'll use a line shapefile with two features. You can download the shapefile as a .ZIP file from https://geospatialpython.googlecode.com/svn/paths.zip

Unzip the shapefile into a directory named qgis_data/shapes within your root or home directory.

How to do it...

The steps for this recipe are fairly straightforward. We'll extract the geometry from the first line feature and pass it to the measurement object, as shown here:

  1. First, we must load the QGIS constants library:

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

    lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
    
  3. Grab the features:

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

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

    d = QgsDistanceArea()
    
  6. Then, we must configure the QgsDistanceArea object to use the ellipsoidal mode for accurate measurements in meters:

    d.setEllipsoidalMode...