Calculating Distance Between Latitude Longitude Pairs in Python
January 24th, 2009
Here is a code snippet that I found very helpful thanks to zachary:
I needed to calculate a simple distance between two latitude, longitude pairs in miles and this did the trick. Apparently, its not the most accurate way to do it since the Earth is not a perfect sphere, but its close enough (an error of 0.5% at most I believe).
import math
#
# The following formulas are adapted from the Aviation Formulary
# http://williams.best.vwh.net/avform.htm
#
nauticalMilePerLat = 60.00721
nauticalMilePerLongitude = 60.10793
rad = math.pi / 180.0
milesPerNauticalMile = 1.15078
def calcDistance(lat1, lon1, lat2, lon2):
"""
Caclulate distance between two lat lons in NM
"""
yDistance = (lat2 - lat1) * nauticalMilePerLat
xDistance = (math.cos(lat1 * rad) + math.cos(lat2 * rad)) *
(lon2 - lon1) * (nauticalMilePerLongitude / 2)
distance = math.sqrt( yDistance**2 + xDistance**2 )
return distance * milesPerNauticalMile
Hopefully someone will find this useful as well.









Yep, someone found this useful. In fact, considering the difficulty I was having translating an existing formula in PHP you have saved me having to learn a whole new language.
Thank you.
+1, thanks.
I wanted it in meters so I looked up that conversion and here’s an adaptation:
# adapted from http://www.zachary.com/s/blog/2005/01/12/python_zipcode_geo-programming
import math
nauticalMilePerLat = 60.00721
nauticalMilePerLongitude = 60.10793
rad = math.pi / 180.0
metersPerNauticalMile = 1852
def metersGeoDistance(lat1, lon1, lat2, lon2):
“”"
Calculate distance between two lat lons in miles
“”"
yDistance = (lat2 – lat1) * nauticalMilePerLat
xDistance = (math.cos(lat1 * rad) + math.cos(lat2 * rad)) * (lon2 – lon1) * (nauticalMilePerLongitude / 2)
distance = math.sqrt( yDistance**2 + xDistance**2 )
return distance * metersPerNauticalMile
After writing and posting that, I found this clean function,
http://code.google.com/p/geolocator/source/browse/trunk/geolocator/gislib.py
from this library,
http://code.google.com/p/geolocator/
which can be easy_install-ed from PyPi,
http://pypi.python.org/pypi/geolocator
THANK YOU! My colleagues and I also found this helpful.
thank you, this saved us some time
Thanks
! It was useful. I had to calculate distance between two IP addresses. I used http://api.hostip.info and the above code to get it.
Thank you, this is exactly what I was looking for