Last active
June 20, 2019 08:33
-
-
Save haoliangyu/78971020cd8fffa39821 to your computer and use it in GitHub Desktop.
Python function to calculate distance between two geographic locations
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
from math import radians, cos, sin, asin, sqrt | |
def haversine(lon1, lat1, lon2, lat2): | |
""" | |
Calculate the great circle distance between two points | |
on the earth (specified in decimal degrees) | |
""" | |
# convert decimal degrees to radians | |
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) | |
# haversine formula | |
dlon = lon2 - lon1 | |
dlat = lat2 - lat1 | |
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 | |
c = 2 * asin(sqrt(a)) | |
# 6371 km is the radius of the Earth | |
km = 6371 * c | |
return km |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment