PyQGIS – Creating Line from Angle and Distance

polyline-creationpyqgis

In the user interface of QGIS I have the option to draw lines with the "Advances Digitizing tool", where I can enter coordinates of a point to set the first vertex. To set the second vertex I can now enter the angle and distance and the "Advances Digitizing Tool" sets the point automatically with the fitting coordinates.

Is it possible to do the same thing using PyQGIS? Drawing a line not from a list of points, but from one point, angle and distance?
(I'm a total beginner using PyQGIS.)

Best Answer

This function will create a new point based on: distance (meters), azimuth (degrees) and the starting point start_QgsPoint which is qgis.core.QgsPoint class. Then you can connect the coordinates into a line. This only works with projected coordinate systems.

def new_point_by_distance_and_azimuth(start_QgsPoint, distance, azimuth):
    start_x, start_y = start_QgsPoint.x(), start_QgsPoint.y()
    azimuth_radians = math.radians(azimuth)
    new_x = start_x + distance * math.cos(azimuth_radians)
    new_y = start_y + distance * math.sin(azimuth_radians)
    return qgis.core.QgsPointXY(new_x, new_y)