Skip to content Skip to sidebar Skip to footer

Geodjango: How To Buffer From Point

I want to have a radius based distance search. To do this, I want to create a buffer around a point object in order to filter objects that are inside it. Here is where I am at with

Solution 1:

PostGIS has a method called ST_MakePoint which can create a 2D, 3D or 4D point.

In a previous answer we saw that it is possible to create a custom database function from an existing PostGIS function:

from django.contrib.gis.db.models.functionsimportGeoFuncclassMakePoint(GeoFunc):
    function='ST_MakePoint'

Now we can create a point by annotate()ing and apply the intersects on it:

z = Thing.objects.annotate(pnt=MakePoint('lat', 'lon'))
                 .filter(pnt__intersects=buf)

You can achieve the same effect by utilizing GeoFunc() and F() expressions:

from django.contrib.gis.db.models.functionsimportGeoFunc

z = Thing.objects.annotate(pnt=GeoFunc(
        F('lat'), F('lon'),
        function='ST_MakePoint'
    ).filter(pnt__intersects=buf)

Note: You could consider adding a pnt field in your Thing model and avoid the above.

Solution 2:

I'm not sure what you mean by "buffer", but if you want a radius based distance search you might try using the... distance!

Here is an example with a kilometer metric:

from django.contrib.gis.measure import D

Thing.objects.filter(pnt__distance_lte=(pnt,D(km=distance)))

You should certainly have a look at the docs: https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#distance-lookups

Post a Comment for "Geodjango: How To Buffer From Point"