Page 1 of 1

Calculate Bearing Between 2 GPS coordinates

Posted: Fri Jan 03, 2014 6:57 am
by tacit ronin
Hello all,
I'm trying to use the Haversine formula to calculate the bearing between two GPS coordinates. I've been following this site's directions: http://www.movable-type.co.uk/scripts/latlong.html. This is my code so far:

Code: Select all

import math

#coordinates1
lat1 = 53.32055
lon1 = -1.72972
#coordinates2
lat2 =  53.31861
lon2 =  -1.69972
dlon = lon2-lon1
#use haversine formula
deltaY = math.sin(dlon) * math.cos(lat2)

deltaX = math.cos(lat1)*math.sin(lat2)-math.sin(lat1)*math.cos(lat2)*math.cos(dlon)

#convert to degrees
bearing = (math.atan2(deltaY, deltaX))* (180/math.pi)

#normalize to compass headings
bearing = (bearing + 180) % 360

print 'bearing: ', bearing
print 'deltaY: ', deltaY
print 'deltaX: ', deltaX
However, my result does not match the web site's:

Coordinate 1: (53.32055, -1.72972)
Coordinate 2: ( 53.31861, -1.69972)
My result: 86.21102 degrees
Correct Result: 96.04555 degrees

I'm using IDLE to run the program on a model B Revision 2 Raspberry Pi.
Thank you for any help!

Re: Calculate Bearing Between 2 GPS coordinates

Posted: Fri Jan 03, 2014 8:23 am
by achrn
math.sin and math.cos work in radians, I believe. You are putting in degrees. Your lat and lon need to be converted to radians.

Re: Calculate Bearing Between 2 GPS coordinates

Posted: Fri Jan 03, 2014 1:05 pm
by tacit ronin
Thank you! I converted the coordinates to radians, and everything works well now. Thanks again for your response.

Re: Calculate Bearing Between 2 GPS coordinates

Posted: Fri Jan 03, 2014 3:20 pm
by scruss
A more correct way to do this is to use pyproj:

Code: Select all

import pyproj
g = pyproj.Geod(ellps='WGS84')
(az12, az21, dist) = g.inv(startlong, startlat, endlong, endlat)
This returns the azimuth, back azimuth and distance between two points. The library also has many other useful routines, and doesn't assume the gross simplification of a spherical Earth.

Re: Calculate Bearing Between 2 GPS coordinates

Posted: Sat Jan 04, 2014 12:46 am
by Brookesa05
Prob not a good idea post exactly where you live on the internet. (Nice house tho).
Make up some coords next time