官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 赣州市| 聊城市| 乌恰县| 象山县| 定远县| 延边| 青神县| 根河市| 郑州市| 巴南区| 嘉荫县| 云南省| 长宁县| 宁晋县| 呼玛县| 平和县| 五指山市| 务川| 保定市| 乌审旗| 牡丹江市| 高邮市| 屏山县| 团风县| 陆川县| 昂仁县| 甘洛县| 田阳县| 汨罗市| 淳安县| 博乐市| 八宿县| 宜城市| 泊头市| 化隆| 宁明县| 望奎县| 万荣县| 昂仁县| 松溪县| 丰都县|