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:

  1. First, import the Python math module:
    import math
    
  2. Next, load the layer:
    lyr = QgsVectorLayer("/qgis_data/shapes/paths.shp", "Route", "ogr")
    
  3. Now, grab the features:
    fts = lyr.getFeatures()
    
  4. Then, grab the first line feature:
    route = fts.next()
    
  5. Create the measurement object:
    d = QgsDistanceArea()
    
  6. You must set the ellipsoidal mode to True in order to project the data before calculating the bearing:
    d.setEllipsoidalMode(True)
    
  7. Get all the points as a list:
    points = route.geometry().asPolyline()
    
  8. Get the first point:
    first = points[0]
    
  9. Grab the last point:
    last = points[-1]
    
  10. Calculate the bearing in radians:
    r = d.bearing(first, last)
    
  11. Now convert radians to degrees:
    b = math.degrees(r)
    
  12. Ensure that the bearing is positive:
    if b < 0: b += 360
    
  13. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset