Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Calculate distance between latitude longitude pairs with Python
#!/usr/bin/env python
# Haversine formula example in Python
# Author: Wayne Dyck
import math
def distance(origin, destination):
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2-lat1)
dlon = math.radians(lon2-lon1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
d = radius * c
return d
@AlessandroLorenzi

This comment has been minimized.

Copy link

AlessandroLorenzi commented May 13, 2013

Cool, tnx!

@osph

This comment has been minimized.

Copy link

osph commented May 24, 2013

My question may be very basic or even silly. If I have lat1=40.5, lat2=42, long1=-90 and long2=-93.
Where do I put these values in the above script?

Is the script written in the IDLE window?
Thanks and sorry for this basic, maybe stupid inquiry.
thanks
PHos

@martinym

This comment has been minimized.

Copy link

martinym commented Jun 24, 2013

@osph, you could use the function with those values by adding code like this to the end:

lat1 = 40.5; lat2 = 42; long1 = -90; long2 = -93
print( distance((lat1, long1), (lat2, long2)) )

However it would be better to save the original script in a file namedhaversine.pyand then create separate scripts that use the function defined in it. This makes it a module which could be used with something like the following in these other scripts:

import haversine

lat1 = 40.5; lat2 = 42; long1 = -90; long2 = -93
print( haversine.distance((lat1, long1), (lat2, long2)) )

The script may have been written in IDLE, or any one of several other programming tools, including just a plain text editor -- it doesn't really matter.

@marioidival

This comment has been minimized.

Copy link

marioidival commented May 12, 2014

If i want use with miles? radius can be 3959?

@Hezi-Resheff

This comment has been minimized.

Copy link

Hezi-Resheff commented Jun 24, 2014

Thank you! you just made some Ecologist very happy :)

@nueverest

This comment has been minimized.

Copy link

nueverest commented Feb 14, 2015

@marioidival The units of the equation are determined by the units of 'radius'. Which corresponds to the spherical radius of the Earth.

3959 # radius of the great circle in miles...some algorithms use 3956
6371 # radius in kilometers...some algorithms use 6367
3959 * 5280 # radius in feet
6371 * 1000 # radius in meters

@RosiersRobin

This comment has been minimized.

Copy link

RosiersRobin commented Mar 13, 2017

Can this be modded to work with ALOT of longtitudes and latitudes?

@musicpiano

This comment has been minimized.

Copy link

musicpiano commented Jun 9, 2018

Thank you very much. I study atmospheric science. Your program is useful for me.

@MalyutinS

This comment has been minimized.

Copy link

MalyutinS commented Aug 7, 2018

Vector implementation (you can pass 4 numpy arrays instead of scalar values):

def distance(s_lat, s_lng, e_lat, e_lng):
    
    # approximate radius of earth in km
    R = 6373.0
    
    s_lat = s_lat*np.pi/180.0                      
    s_lng = np.deg2rad(s_lng)     
    e_lat = np.deg2rad(e_lat)                       
    e_lng = np.deg2rad(e_lng)  
    
    d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2
    
    return 2 * R * np.arcsin(np.sqrt(d)) 
@killerontherun1

This comment has been minimized.

Copy link

killerontherun1 commented Aug 30, 2018

Thanks so much! Just what I needed.

@Edward-Aidi

This comment has been minimized.

Copy link

Edward-Aidi commented Dec 12, 2018

Great! Thanks!

@Zagroz

This comment has been minimized.

Copy link

Zagroz commented Mar 9, 2019

Hello, thank you very much for this masterpiece. But my concern is how to do so when you have an excel file, I have bunch of cities and finding the distance from those cities to one reference point (which is also a city). Thanks

@fudigit

This comment has been minimized.

Copy link

fudigit commented Jun 1, 2019

Thanks much , this helped a machine learning engineer.

@AnguKumar

This comment has been minimized.

Copy link

AnguKumar commented Jun 1, 2019

Hi
I need to find the distance between two gps trajectories, from US 101 dataset, which covers totally 2000ft distance.

"Vehicle ID","Frame ID","Total Frames","Global Time","Local X","Local Y","Global X","Global Y","V_Len","V_Width","V_Class","V_Vel","V_Acc","Lane_ID","Pre_Veh","Fol_Veh","Spacing","Headway"

2,13,437,1118846980200,16.467,35.381,6451137.641,1873344.962,14.5,4.9,2,40.00,0.00,2,0,0,0.00,0.00
2,14,437,1118846980300,16.447,39.381,6451140.329,1873342.000,14.5,4.9,2,40.00,0.00,2,0,0,0.00,0.00
2,15,437,1118846980400,16.426,43.381,6451143.018,1873339.038,14.5,4.9,2,40.00,0.00,2,0,0,0.00,0.00
2,16,437,1118846980500,16.405,47.380,6451145.706,1873336.077,14.5,4.9,2,40.00,0.00,2,0,0,0.00,0.00
2,17,437,1118846980600,16.385,51.381,6451148.395,1873333.115,14.5,4.9,2,40.00,0.00,2,0,0,0.00,0.00

But when I am trying to find the distance between two adjacent points of the same vehicle, Its giving

in more than 20 kms..

Can any you help me to find the distance between two adjacent trajectories
I need to segregate the dataset into subsections covering 200ft distance each..

@joaovs12

This comment has been minimized.

Copy link

joaovs12 commented Sep 4, 2019

Hello, I have a list with 700 cities and I want to find the city where the sum of distances will be minimun
I defined a function that will give me that sum, but what I should do to find the lat,long where the sum of distances will be minimum? tks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.