Skip to content

Instantly share code, notes, and snippets.

@nootrope
Last active August 29, 2015 14:04
Show Gist options
  • Save nootrope/4eaab2263c3d4631b3c8 to your computer and use it in GitHub Desktop.
Save nootrope/4eaab2263c3d4631b3c8 to your computer and use it in GitHub Desktop.
Python implementation of the Haversine function to convert GPS coords to kilometers and miles.
def haversine(pos1, pos2):
# From http://stackoverflow.com/a/18144531/3788069
lat1 = float(pos1['lat'])
long1 = float(pos1['long'])
lat2 = float(pos2['lat'])
long2 = float(pos2['long'])
degree_to_rad = float(pi / 180.0)
d_lat = (lat2 - lat1) * degree_to_rad
d_long = (long2 - long1) * degree_to_rad
a = pow(sin(d_lat / 2), 2) + cos(lat1 * degree_to_rad) * cos(lat2 * degree_to_rad) * pow(sin(d_long / 2), 2)
c = 2 * atan2(sqrt(a), sqrt(1 - a))
km = 6367 * c
mi = 3956 * c
return {"km":km, "miles":mi}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment