Skip to content

Instantly share code, notes, and snippets.

@daliposc
Last active December 6, 2019 21:22
Show Gist options
  • Save daliposc/63f36d04eb1a14fb8f11b9e9e3e9305d to your computer and use it in GitHub Desktop.
Save daliposc/63f36d04eb1a14fb8f11b9e9e3e9305d to your computer and use it in GitHub Desktop.
Calculates the bearing and distance for each segment of a Linestring and stores the data in a Points layer with a feature for each vertex of the original line.

This is perhaps an overly complicated way to complete this task. For example, it's probably simpler to use the "Extract Vertices" and "Explode Lines" tools in QGIS. Then use the Field Calculator on the exploded lines to calculate bearing: degrees(azimuth(point_n($geometry,1),point_n($geometry,2))) and distance: $length. Then join the results to the extracted vertices.

The results of the script look like this in QGIS:

from math import pi
line_lyr = QgsProject.instance().mapLayersByName('line')[0]
line_geom = line_lyr.getGeometry(1)
results_lyr = QgsVectorLayer(f'Point?crs={line_lyr.sourceCrs().authid()}', 'temp', 'memory')
results_provider = results_lyr.dataProvider()
results_provider.addAttributes([QgsField('id', QVariant.Int),
QgsField('dist_along_line', QVariant.Double),
QgsField('dist_from_previous_point', QVariant.Double),
QgsField('bearing_from_previous_point', QVariant.Double)])
results_lyr.updateFields()
for i, vertex in enumerate(line_geom.vertices()):
result_feature = QgsFeature()
result_feature.setGeometry(vertex)
if i == 0:
result_feature.setAttributes([i, 0.0, 0.0, 0.0])
else:
dist_along_line = line_geom.distanceToVertex(i)
dist_from_previous_point = dist_along_line - line_geom.distanceToVertex(i-1)
bearing_from_previous_point = line_geom.interpolateAngle(dist_along_line - dist_from_previous_point/2) * 180/pi
result_feature.setAttributes([i, dist_along_line, dist_from_previous_point, bearing_from_previous_point])
results_provider.addFeatures([result_feature])
results_lyr.updateExtents()
QgsProject.instance().addMapLayer(results_lyr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment