Python: Calculate bearing between two lat/long
The code for finding the bearing is fine. But you just need to add math.radians when finding X and Y.
import numpy
import math
def get_bearing(lat1, long1, lat2, long2):
dLon = (long2 - long1)
x = math.cos(math.radians(lat2)) * math.sin(math.radians(dLon))
y = math.cos(math.radians(lat1)) * math.sin(math.radians(lat2)) - math.sin(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.cos(math.radians(dLon))
brng = numpy.arctan2(x,y)
brng = numpy.degrees(brng)
return brng
Have you considered using pyproj
to do the calculations instead of rolling your own?:
import pyproj
geodesic = pyproj.Geod(ellps='WGS84')
fwd_azimuth,back_azimuth,distance = geodesic.inv(long1, lat1, long2, lat2)
In this example fwd_azimuth
is the bearing you are after and back_azimuth
is inverse bearing (going the opposite direction).
I used WGS84 here, so you would need to replace with correct coordinate system, and need to rewrite ensure lat/long are correct type of coordinates for geodesic.inv()
. But using a well-tested, existing geo-spatial lib will likely save you a lot of hair pulling.
Ended up changing the function:
from geographiclib.geodesic import Geodesic
...
def get_bearing(lat1, lat2, long1, long2):
brng = Geodesic.WGS84.Inverse(lat1, long1, lat2, long2)['azi1']
return brng