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

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.

主站蜘蛛池模板: 乐山市| 夏邑县| 北安市| 娱乐| 巢湖市| 宁城县| 凌云县| 蕲春县| 常德市| 名山县| 荆门市| 原阳县| 翼城县| 桃园市| 新余市| 新昌县| 乌鲁木齐市| 博野县| 吉安县| 封开县| 宜兰市| 天气| 阿瓦提县| 稷山县| 集安市| 广元市| 嵩明县| 仁化县| 乐山市| 梧州市| 焦作市| 灌南县| 郓城县| 绵竹市| 泊头市| 汪清县| 南和县| 敖汉旗| 沙坪坝区| 安泽县| 寿宁县|