In this recipe, we'll measure the distance along a line with multiple vertices.
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.
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:
from qgis.core import QGis
lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
fts = lyr.getFeatures()
route = fts.next()
d = QgsDistanceArea()
d.setEllipsoidalMode(True)
measureLine
method:m = d.measureLine(route.geometry().asPolyline())
d.convertMeasurement(m, QGis.Meters, QGis.NauticalMiles, False)
Ensure that your output looks similar to the following:
(2314126.583384674, 7)
The QgsDistanceArea object can perform any type of measurement, based on the method you call. When you convert the measurement from meters (represented by 0) to miles (identified by the number 7), you will get a tuple with the measurement in miles and the unit identifier. The QGIS API documentation shows the values for all the unit constants