3

I am trying to create a line feature as the result of another line in PyQGIS. The new line should start, where the old "ends", face the "same direction" and should have a defined length of X.

Unfortunately, the direction of both lines is not the same using the following code. What is wrong?:

p1 = QgsPointXY(14.18064, 50.63963)
p2 = QgsPointXY(14.15027, 50.66042)

d = QgsDistanceArea()
d.setEllipsoid('WGS84')
degrees = p1.azimuth(p2)
rad = math.radians(degrees)
# distance is 1000m
d_upfront = d.computeSpheroidProject(p2,1000,rad)
line_layer = QgsVectorLayer("Linestring?crs=4326", "Measurements AUTO", "memory")
QgsProject.instance().addMapLayer(line_layer)
line = QgsGeometry.fromPolylineXY([p1, p2])
feat = QgsFeature()
feat.setGeometry(line)
line2 = QgsGeometry.fromPolylineXY([p2, d_upfront])
feat2 = QgsFeature()
feat2.setGeometry(line2)
provider = line_layer.dataProvider()
provider.addFeatures([feat,feat2])

provider.forceReload()
line_layer.reload()
line_layer.triggerRepaint()

The example shows the difference: enter image description here

1 Answer 1

2

The calculation of the azimuth is not the right way to do it. You will get ideal results if you switch to a bearing calculation:

p1 = QgsPointXY(14.18064, 50.63963)
p2 = QgsPointXY(14.15027, 50.66042)
d = QgsDistanceArea()
d.setEllipsoid('WGS84')
# distance is 1000m
d_upfront = d.computeSpheroidProject(p2,1000,d.bearing(p1,p2))
line_layer = QgsVectorLayer("Linestring?crs=EPSG:4326", "Measurements AUTO", "memory")
QgsProject.instance().addMapLayer(line_layer)
line = QgsGeometry.fromPolylineXY([p1, p2])
feat = QgsFeature()
feat.setGeometry(line)
line2 = QgsGeometry.fromPolylineXY([p2, d_upfront])
feat2 = QgsFeature()
feat2.setGeometry(line2)
provider = line_layer.dataProvider()
provider.addFeatures([feat,feat2])

provider.forceReload()
line_layer.reload()
line_layer.triggerRepaint()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.