Calculate the distance between two coordinates with Python

11,434

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])
Share:
11,434

Related videos on Youtube

V. Andy
Author by

V. Andy

Updated on June 04, 2022

Comments

  • V. Andy
    V. Andy almost 2 years

    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?

  • Gianmar
    Gianmar over 5 years
    The output is in meters?, that not worked for me.
  • Gianmar
    Gianmar over 5 years
    The output is in Km, for meters was neded add *1000 to return
  • pepece
    pepece over 4 years
    you must convert to radian first: lon_1, lat_1, lon_2, lat_2 = map(math.radians, [lon_1, lat_1, lon_2, lat_2])
  • cs95
    cs95 over 4 years
    @pepece I'd implicitly assumed the coords to be in radians since that's how I wrote the function for myself. Added a note in the answer, thanks for pointing it out!