Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
compass bearing between two points in Python
def calculate_initial_compass_bearing(pointA, pointB):
"""
Calculates the bearing between two points.
The formulae used is the following:
θ = atan2(sin(Δlong).cos(lat2),
cos(lat1).sin(lat2) − sin(lat1).cos(lat2).cos(Δlong))
:Parameters:
- `pointA: The tuple representing the latitude/longitude for the
first point. Latitude and longitude must be in decimal degrees
- `pointB: The tuple representing the latitude/longitude for the
second point. Latitude and longitude must be in decimal degrees
:Returns:
The bearing in degrees
:Returns Type:
float
"""
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = math.radians(pointA[0])
lat2 = math.radians(pointB[0])
diffLong = math.radians(pointB[1] - pointA[1])
x = math.sin(diffLong) * math.cos(lat2)
y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1)
* math.cos(lat2) * math.cos(diffLong))
initial_bearing = math.atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = math.degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing

Exactly what I was looking for. Nice work.

ehippy commented Mar 9, 2014

Likewise! This was perfect!

Thanks. This is perfect for my pet project.

sgreifzu commented May 5, 2015

Thank you!

I was wondering why my ships in ksp were never exactly on target, this is great!

thanks -- this is much better than what I was using before!

jligeza commented Apr 13, 2016

At last an algorithm that just works. Thank you.

Great {Pro}

This works great! Thank you.

Awesome!

quieterkali commented Apr 17, 2017 edited

Thank you very much 🥇

What is the license for this code, @jeromer?

up !

Very nice, especially all the explanation. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment