Search code examples
pythondjangogispostgisgeodjango

How to calculate distance between points on python side of my application in way that is consistent in what database does


I'm writing an application that makes heavy use of geodjango (on PostGis) and spatial lookups. Distance queries on database side work great, but now I have to calculate distance between two points on python side of application (these points come from models obtained using separate queries).

I can think of many ways that would calculate this distance, but I want to know do it in manner that is consistent with what the database will output.

Is there any magic python function that calculates distance between two points given in which SRID they are measured? If not what other approach could you propose.


Solution

  • You can use the haversine function from this question:

    >>> from math import radians, cos, sin, asin, sqrt
    >>> 
    >>> def haversine(lon1, lat1, lon2, lat2):
    ...     """
    ...     Calculate the great circle distance between two points 
    ...     on the earth (specified in decimal degrees)
    ...     """
    ...     # convert decimal degrees to radians 
    ...     lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    ...     # haversine formula 
    ...     dlon = lon2 - lon1 
    ...     dlat = lat2 - lat1 
    ...     a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    ...     c = 2 * asin(sqrt(a)) 
    ...     km = 6367 * c
    ...     return km 
    ... 
    >>> haversine(-1.7297, 53.3205, -1.6997, 53.3186)
    2.0025842109026413