Skip to content

Instantly share code, notes, and snippets.

@nschairer
Created February 21, 2020 03:03
Show Gist options
  • Save nschairer/0e288f84e8bfc37b5ca9593c15d28281 to your computer and use it in GitHub Desktop.
Save nschairer/0e288f84e8bfc37b5ca9593c15d28281 to your computer and use it in GitHub Desktop.
Function to compute distance in Miles or Kilometers between two latitude, longitude points on Earth using the Haversine formula
'''Haversine formula - Shortest distance between two points on a sphere
Steps:
1) Convert lat,long for two points from degrees to radians --> divide by 180/pi == 57.29577951
2) Earth radius in miles -> 3958.8, Km -> 6371
3) Formula
hav(lat2 - lat1) + cos(lat1)*cos(lat2)*hav(long2-long1)
hav(theta) = sin^2(theta/2) = (1 - cos(theta)) / 2
Let h = hav(theta)
d = radius * archav(h) = 2 * radius * arcsin(sqrt(h))
Refs:
https://en.wikipedia.org/wiki/Haversine_formula "the haversine formula and law of cosines cannot be guaranteed correct to better than 0.5%."
'''
from math import radians, cos, sin, asin, sqrt
def distance(coords1,coords2,unit='Miles'):
'''Function to find the distance between two latitude, longitude points on earth
Args:
coords1 (tuple): Tuple containing the latitude/longitude of point 1
coords2 (tuple): Tuple containing the latitude/longitude of point 2
unit (string): Value to switch unit of measure, default is Miles other option is Kilometers
Returns:
distance (float): Distance calculated between two points on a sphere using the haversine formula
'''
lat1 = radians(coords1[0])
long1 = radians(coords1[1])
lat2 = radians(coords2[0])
long2 = radians(coords2[1])
delta_long = long2 - long1
delta_lat = lat2 - lat1
#Compute haversine of two points
a = sin(delta_lat / 2)**2 + cos(lat1) * cos(lat2) * sin(delta_long/2)**2
#Compute distance by completing the formula
c = 2 * asin(sqrt(a))
#Select radius value for earth based on unit
r = 3958.8
if unit == 'Kilometers':
r = 6371
return c * r
if __name__ == "__main__":
#Philly
point1 = (39.952031,-75.166068)
#NYC
point2 = (40.709422,-74.006358)
print(distance(point1,point2),'Miles')
print(distance(point1,point2,unit='Kilometers'),'Kilometers')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment