python :: Calculating the distance between two locations…

How far is it from point a to point b? There are complicated ways to answer this question, that e.g. takes into account whether you’re walking or driving etc. However, if you only need the approximate distance “as the crow flies”, some simple math is sufficient.

I’m assuming you’ve used Google’s geo-coding, or’s postal code search, etc., and now have locations with lat and lng attributes.

The Earth isn’t a perfect sphere, among many non-spherical properties, it’s actually fatter around the equator than between the poles: The algorithm doesn’t take any of this into account, and instead uses a single value for the Earth’s radius. Assuming you’re not going very far (i.e. “halfway around the globe”, the result will probably not be too far off, YMMV of course).


import math

def cosrad(n):
    "Return the cosine of ``n`` degrees in radians."
    return math.cos(math.radians(n))
def haversine((lat1, long1), (lat2, long2)):
    """Calculate the distance between two points on earth.
    earth_radius = 6371  # km
    dLat = math.radians(lat2 - lat1)
    dLong = math.radians(long2 - long1)

    a = (math.sin(dLat / 2) ** 2 +
         cosrad(lat1) * cosrad(lat2) * math.sin(dLong / 2) ** 2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    d = earth_radius * c
    return d

def distance(a, b):
    "Return the distance between two points that have .lat and .lng members."
    return haversine(
        (float(, float(a.lng)),
        (float(, float(b.lng)))
This entry was posted in Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *