User avatar
tacit ronin
Posts: 4
Joined: Fri Jan 03, 2014 6:42 am

Calculate Bearing Between 2 GPS coordinates

Fri Jan 03, 2014 6:57 am

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!
Last edited by tacit ronin on Sun Jan 05, 2014 3:57 am, edited 2 times in total.

achrn
Posts: 412
Joined: Wed Feb 13, 2013 1:22 pm

Re: Calculate Bearing Between 2 GPS coordinates

Fri Jan 03, 2014 8:23 am

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.

User avatar
tacit ronin
Posts: 4
Joined: Fri Jan 03, 2014 6:42 am

Re: Calculate Bearing Between 2 GPS coordinates

Fri Jan 03, 2014 1:05 pm

Thank you! I converted the coordinates to radians, and everything works well now. Thanks again for your response.

User avatar
scruss
Posts: 3212
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Calculate Bearing Between 2 GPS coordinates

Fri Jan 03, 2014 3:20 pm

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.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

Brookesa05
Posts: 22
Joined: Mon Apr 15, 2013 7:53 pm

Re: Calculate Bearing Between 2 GPS coordinates

Sat Jan 04, 2014 12:46 am

Prob not a good idea post exactly where you live on the internet. (Nice house tho).
Make up some coords next time

Return to “Python”