4

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?

cs95
  • 379,657
  • 97
  • 704
  • 746
V. Andy
  • 51
  • 1
  • 1
  • 4
  • Possible duplicate of [Calculate distance between two latitude-longitude points? (Haversine formula)](https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula) – Mark Rotteveel Jun 25 '17 at 09:29

1 Answers1

9

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])
cs95
  • 379,657
  • 97
  • 704
  • 746
  • The output is in meters?, that not worked for me. – Gianmar Jul 31 '18 at 18:23
  • The output is in Km, for meters was neded add *1000 to return – Gianmar Jul 31 '18 at 20:53
  • 2
    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]) – pepece Oct 25 '19 at 07:24
  • 1
    @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! – cs95 Oct 25 '19 at 07:47