Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the distance between two coordinates with Python [closed]

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?

like image 976
V. Andy Avatar asked Mar 09 '23 18:03

V. Andy


1 Answers

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])
like image 79
cs95 Avatar answered Mar 11 '23 07:03

cs95