Calculate distance between latitude longitude pairs with Python

Published on October 05, 2009

The Haversine formula is an equation that can be used to find great-circle distances between two points on a sphere from their longitudes and latitudes. When this formula is applied to the earth the results are an approximation because the Earth is not a perfect sphere. The currently accepted (WGS84) radius at the equator is 6378.137 km and 6356.752 km at the polar caps. For aviation purposes the FAI uses a radius of 6371.0 km

#!/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

Saving the above script as haversine.py you can also use it interactively within the Python shell like this,

>>> import haversine
>>> seattle = [47.621800, -122.350326]
>>> olympia = [47.041917, -122.893766]
>>> haversine.distance(seattle, olympia)
76.386615799548693
>>>

Comments are closed.

Comments have been closed for this post.