Skip to content

Instantly share code, notes, and snippets.

@clayadavis
Last active May 3, 2017 01:27
Show Gist options
  • Save clayadavis/11f31eb7d5c964e19cf360174c7f5302 to your computer and use it in GitHub Desktop.
Save clayadavis/11f31eb7d5c964e19cf360174c7f5302 to your computer and use it in GitHub Desktop.
import math
from collections import namedtuple
def haversine_distance(origin, destination):
""" Haversine formula to calculate the distance between two lat/long points on a sphere """
radius = 6371 # FAA approved globe radius in km
dlat = math.radians(destination.lat-origin.lat)
dlon = math.radians(destination.lng-origin.lng)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(origin.lat)) \
* math.cos(math.radians(destination.lat)) * math.sin(dlon/2) * math.sin(dlon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = radius * c
# Return distance in km
# return int(math.floor(d))
return d
if __name__ == "__main__":
LatLng = namedtuple('LatLng', 'lat, lng')
origin = LatLng(51.507222, -0.1275) # London
destination = LatLng(37.966667, 23.716667) # Athens
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment