Search code examples
pythongoogle-app-enginegpsgeocodingdatastore

Way to let user search by GPS


I am building an application on google app engine with python and I have a Location entity that has a GPS property. This property is stored as a string (though I could change this if need be) and I want to let the user type in a location and have my program return all the sites within 5 points of latitude or longitude.

I have the following code which gives me the location in GPS that the user is searching for but I am not sure what I can do from there and how I can do a query for all the GPS locations within my bounds.

class Map(BlogHandler):
    def get(self):
        #do some stuff here
    def post(self):
        inputlocation = self.request.get("q")

        #this returns the GPS location that the user searched for
        g = geocoders.Google()
        place, (lat, lng) = g.geocode(inputlocation)

        #I would like to be able to do something like this         
        bound = 5
        upper = GPSlocation + bound
        lower = GPSlocation - bound
        left = GPSlocation + bound
        right = GPSlocation - bound

locations = db.GqlQuery("select * from Location where GPSlocation.lat<:1 and where GPSlocation.lat>:2 and where GPSlocation.long <:3 and where GPSlocation.long >:4 order by created desc limit 20", upper, lower, left, right)

        self.render('map.html', locations=locations, centerlocation=GPSlocation)

Solution

  • searching by 5 points is pretty easy, since that's just a square area:

    select ...
    where (GPSlocation.lat BETWEEN (:1 - 5) AND (:2 + 5))
       and (GPSlocation.long BETWEEN (:3 - 5) AND (:4 + 5))
    

    if you were targeting a circular boundary, then you'd be in for a bit more math.

    note that your where condition in your own query is invalid and will cause a syntax error. WHERE syntax is

    WHERE (condition) AND (condition) ...
    

    not

    WHERE (condition) AND WHERE (condition) ...
                          ^^^^^---syntax error