Last active
February 21, 2024 13:31
-
-
Save jeromer/2005586 to your computer and use it in GitHub Desktop.
compass bearing between two points in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# LICENSE: public domain | |
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 |
Thanks for providing a good option. It is a really helpful for us.
Dude, I want to have kids from you <3. Excellent work!!!
Much faster than importing obspy.geodetics.gps2dist_azimuth
Thanks a lot
Great work! Thanks very much 👍
This is good enough for me, though I think the algorithm is a bit simplified. It will probably give inaccurate results when used over long distances or when one is close to the poles. I find it strange that there isn't anything easily available through the geopy library.
Excellent work
Thanks. Fixed my problem with this one.
Thank you this worked 👯
I like this. I'll combine this with Vincenty's formula to return bearing and distance.
Javascript version: https://gist.github.com/av01d/f7f97cf1217945fc4628c6c97e916122
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!