Last active
May 3, 2017 01:27
-
-
Save clayadavis/11f31eb7d5c964e19cf360174c7f5302 to your computer and use it in GitHub Desktop.
Haversine formula, from https://news.ycombinator.com/item?id=9282102
This file contains 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
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