2

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
jb.
  • 23,300
  • 18
  • 98
  • 136

3 Answers3

3

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
Community
  • 1
  • 1
jterrace
  • 64,866
  • 22
  • 157
  • 202
1

If you want consistency with the way PostGIS does it you probably want to use something better than a haversine implementation. I suggest you look at the Python version of GeographicLib that will do the calculations far more accurately.

You'd get better answers on gis.stackexchange

jwd630
  • 4,529
  • 1
  • 20
  • 22
0

Use the appropriate data connection to execute the SQL function that you're already using, then retrieve that... Keeps everything consistent.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280