Calculating the bearing of a line
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.
Getting ready
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.
How to do it...
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:
- First, import the Python math module:
import math
- Next, load the layer:
lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
- Now, grab the features:
fts = lyr.getFeatures()
- Then, grab the first line feature:
route = fts.next()
- Create the measurement object:
d = QgsDistanceArea()
- You must set the ellipsoidal mode to
True
in order to project the data before calculating the bearing:d.setEllipsoidalMode(True)
- Get all the points as a list:
points = route.geometry().asPolyline()
- Get the first point:
first = points[0]
- Grab the last point:
last = points[-1]
- Calculate the bearing in radians:
r = d.bearing(first, last)
- Now convert radians to degrees:
b = math.degrees(r)
- Ensure that the bearing is positive:
if b < 0: b += 360
- View the output:
print b
Verify that the bearing is close to the following number:
320.3356091875395
How it works...
The default output of the bearing calculation is in radians. However, the Python math
module makes conversion a snap of the fingers. If the conversion of degrees results in a negative number, most of the time we will want to add that number to 360 in order to get a compass bearing, as we did here.