Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calculates distance between two points on earth using their latitudes and longitudes
#!/usr/bin/env python3
'''Calculates Haversian distance between two points on earth'''
from math import (sqrt, radians, sin, cos, atan2)
def haversian_dist(loc1, loc2):
'''Calculates Haversian distance between two points on earth
loc1 and loc2 are (lat, long) of two points'''
radius = 6373.0 # approx earth radius in km
lat1, lon1, lat2, lon2 = map(radians, loc1 + loc2)
lon_diff, lat_diff = lon2 - lon1, lat2 - lat1
a = sin(lat_diff / 2)**2 + cos(lat1) * cos(lat2) * sin(lon_diff / 2)**2
distance = radius * 2 * atan2(sqrt(a), sqrt(1 - a))
return distance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment