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

后端 未结 6 958
轮回少年
轮回少年 2020-12-07 21:49

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

6条回答
  •  难免孤独
    2020-12-07 21:52

    Just to follow up on jboxer's answer, here's the whole thing as part of a custom manager with some of the hard-coded stuff turned into variables:

    class LocationManager(models.Manager):
        def nearby_locations(self, latitude, longitude, radius, max_results=100, use_miles=True):
            if use_miles:
                distance_unit = 3959
            else:
                distance_unit = 6371
    
            from django.db import connection, transaction
            cursor = connection.cursor()
    
            sql = """SELECT id, (%f * acos( cos( radians(%f) ) * cos( radians( latitude ) ) *
            cos( radians( longitude ) - radians(%f) ) + sin( radians(%f) ) * sin( radians( latitude ) ) ) )
            AS distance FROM locations_location HAVING distance < %d
            ORDER BY distance LIMIT 0 , %d;""" % (distance_unit, latitude, longitude, latitude, int(radius), max_results)
            cursor.execute(sql)
            ids = [row[0] for row in cursor.fetchall()]
    
            return self.filter(id__in=ids)
    

提交回复
热议问题