Sometimes, you need to know the compass bearing of a line to create specialized symbology or use as input in a spatial calculation. Even though its name only mentions distance and area, the versatile QgsDistanceArea
object includes this function as well. In this recipe, we'll calculate the bearing of the end points of a line. However, this recipe will work with any two points.
We'll use the line shapefile used in a previous recipe. 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 to be performed are as simple as getting the two points we need and running them through the bearing function, converting from radians to degrees, and then converting to a positive compass bearing:
import math
lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
fts = lyr.getFeatures()
route = fts.next()
d = QgsDistanceArea()
True
in order to project the data before calculating the bearing:d.setEllipsoidalMode(True)
points = route.geometry().asPolyline()
first = points[0]
last = points[-1]
r = d.bearing(first, last)
b = math.degrees(r)
if b < 0: b += 360
print b
Verify that the bearing is close to the following number:
320.3356091875395