Created
April 14, 2011 17:38
-
-
Save jsundram/920023 to your computer and use it in GitHub Desktop.
simple haversine implementation from description on wikipedia
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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