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

后端 未结 6 933
轮回少年
轮回少年 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 22:07

    Following jboxer's response

    def find_cars_within_miles_from_postcode(request, miles, postcode=0):
    
        # create cursor for RAW query
        cursor = connection.cursor()
    
        # Get lat and lon from google
        lat, lon = getLonLatFromPostcode(postcode)
    
        # Gen query
        query = "SELECT id, ((ACOS(SIN("+lat+" * PI() / 180) * SIN(lat * PI() / 180) + COS("+lat+" * PI() / 180) * COS(lat * PI() / 180) * COS(("+lon+" - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM app_car HAVING distance<='"+miles+"' ORDER BY distance ASC"
    
        # execute the query
        cursor.execute(query)
    
        # grab all the IDS form the sql result
        ids = [row[0] for row in cursor.fetchall()]
    
        # find cars from ids
        cars = Car.objects.filter(id__in=ids)
    
        # return the Cars with these IDS
        return HttpResponse( cars )
    

    This returns my cars from x amount of miles, this works well. However the raw query returned how far they were from a certain location, i think the fieldname was 'distance'.

    How can i return this field 'distance' with my car objects?

提交回复
热议问题