# How to calculate azimuth in QGIS field calculator?

Is there any way to calculate the azimuth of two points in the QGIS field calculator? The coordinates are stored in an attribute table.

``````x1 | y1 | x2 | y2
``````

You can use function editor tab in the field calculator and make your azimuth function like this:

``````from qgis.core import *
from qgis.gui import *
@qgsfunction(args="auto", group='Custom')
def azimuth(x1,y1,x2,y2,feature,parent):
p1 = QgsPoint(x1,y1)
p2 = QgsPoint(x2,y2)
a = p1.azimuth(p2)
if a < 0:
a += 360
return a
``````

Once you run/save it (and just to make sure restart the calculator) you should be able to use this function in the expression tab either by typing it or selecting from Functions list under custom as:

``````azimuth(x1,y1,x2,y2) #or variation azimuth("x1","y1","x2","y2")
``````

All credit for this goes to Anita Graser and her How to create illuminated contours, Tanaka-style.

New versions of QGIS ship with an azimuth function out of the box:

• This works great. A tip: For using this function with a line, you can supply 'start_point(\$geometry)' and 'end_point(\$geometry)' as point_a and point_b – spatialthoughts Apr 3 '18 at 6:11