I have a map where they find several points (lat/long) and want to know the distance that exists between them.
So, given a set of lat/long coordinates, how can I compute the distance between them in python?
I once wrote a python version of this answer. It details the use of the Haversine formula to calculate the distance in kilometers.
import math
def get_distance(lat_1, lng_1, lat_2, lng_2):
d_lat = lat_2 - lat_1
d_lng = lng_2 - lng_1
temp = (
math.sin(d_lat / 2) ** 2
+ math.cos(lat_1)
* math.cos(lat_2)
* math.sin(d_lng / 2) ** 2
)
return 6373.0 * (2 * math.atan2(math.sqrt(temp), math.sqrt(1 - temp)))
Ensure the coordinates being passed to the function are in radians. If they're in degrees, you can convert them first:
lng_1, lat_1, lng_2, lat_2 = map(math.radians, [lng_1, lat_1, lng_2, lat_2])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With