Filter zipcodes by proximity in Django with the Spherical Law of Cosines

Posted by spiffytech on Stack Overflow See other posts from Stack Overflow or by spiffytech
Published on 2009-12-16T19:12:28Z Indexed on 2010/06/13 23:12 UTC
Read the original article Hit count: 306

Filed under:
|
|
|

I'm trying to handle proximity search for a basic store locater in Django. Rather than haul PostGIS around with my app just so I can use GeoDjango's distance filter, I'd like to use the Spherical Law of Cosines distance formula in a model query. I'd like all of the calculations to be done in the database in one query, for efficiency.

An example MySQL query from The Internet implementing the Spherical Law of Cosines like this:

SELECT id, ( 
    3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * 
    cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * 
    sin( radians( lat ) ) ) 
) 
AS distance FROM stores HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

The query needs to reference the Zipcode ForeignKey for each store's lat/lng values. How can I make all of this work in a Django model query?

© Stack Overflow or respective owner

Related posts about python

Related posts about django