Skip to content

Instantly share code, notes, and snippets.

@jsundram
Created April 14, 2011 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsundram/920023 to your computer and use it in GitHub Desktop.
Save jsundram/920023 to your computer and use it in GitHub Desktop.
simple haversine implementation from description on wikipedia
from math import pi, sin, cos, atan2, sqrt
def haversine_distance(loc1, loc2):
"""Haversine formula - give coordinates as (lat_decimal, lon_decimal) tuples. Returns distance in miles"""
earth_radius = 6371.0 # km
to_radians = lambda x : x * pi / 180.0
lat1, lon1 = map(to_radians, loc1)
lat2, lon2 = map(to_radians, loc2)
# haversine formula
hdlat = (lat2 - lat1) / 2.0
hdlon = (lon2 - lon1) / 2.0
a = sin(hdlat)**2 + cos(lat1) * cos(lat2) * sin(hdlon)**2
c = 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
km = earth_radius * c
return km * 0.621371
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment