[GIS] Geodjango: Using Lat / Lon to Buffer from Point

bufferfiltergeodjangolatitude longitudepoint

I want to have a radius based distance search. To do this, I want to create a buffer around a point object so that I can filter objects that are inside this buffer, a method that I learned based on a google groups post.

I want to use latitude and longitude in my model definition so that I can easily put the information into my google map later:

class Thing:
    latitude = models.FloatField()
    longitude = models.FloatField()

The only problem is trying to filter results based on lat / lon coordinates:

>>> lat = 37.7762179974
>>> lon = -122.411562492
>>> from django.contrib.gis.geos import Point
>>> pnt = Point(lat, lon)
>>> buf = pnt.buffer(0.0001)

How can I do something like this?

qs = Thing.objects.filter((lat, long)__intersects=buf)

Best Answer

There is no reason to avoid defining a PointField, particularly because you want to utilize GeoDjango's geometry functions. You should define your class as such:

from django.contrib.gis.db import models

class Thing(models.Model):
    objects = models.GeoManager()
    point = models.PointField(srid=4326)

    def latitude(self):
        return self.point.y

    def longitude(self):
        return self.point.x

Then, if you need a convenient way of accessing latitude and longitude (though it is already pretty convenient), you can use the methods set on the class instances:

from app.models import Thing

foo = Thing('POINT(-86 42)')

foo.point.x # Returns -86.0
foo.point.y # Returns 42.0

foo.longitude() # Returns -86.0
foo.latitude() # Returns 42.0