Last active
February 10, 2024 08:34
-
-
Save kevinlinxc/9a44911b7cb84ed182669f1716f8f555 to your computer and use it in GitHub Desktop.
Haversine Distance Calculator
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
"""Calculate the difference between two GPS coordinates using the Haversine formula""" | |
from math import radians, cos, sin, sqrt, atan2 | |
def haversine(coord1, coord2): | |
# Radius of the Earth in kilometers | |
R = 6378.137 | |
# Converting coordinates from degrees to radians | |
lat1, lon1 = radians(coord1[0]), radians(coord1[1]) | |
lat2, lon2 = radians(coord2[0]), radians(coord2[1]) | |
# Differences in coordinates | |
dlat = lat2 - lat1 | |
dlon = lon2 - lon1 | |
# Haversine formula | |
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 | |
c = 2 * atan2(sqrt(a), sqrt(1 - a)) | |
distance = R * c | |
return distance | |
brian = 49.2602538, -123.2488872 | |
me = 49.2643602, -123.2522186 | |
print("Distance:", haversine(brian, me), "km") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment