[Django]-How can I measure distance with tastypie and geodjango?

2👍

Got it working, here is an example for posterity:

In the api.py, create a Resource that looks like this:

from django.contrib.gis.geos import *

class LocationResource(ModelResource):
    class Meta:
        queryset = Building.objects.all()
        resource_name = 'location'

    def apply_sorting(self, objects, options=None):
        if options and "longitude" in options and "latitude" in options:
            pnt = fromstr("POINT(" + options['latitude'] + " " + options['longitude'] + ")", srid=4326)
            return objects.filter(building_point__distance_lte=(pnt, 500))

        return super(LocationResource, self).apply_sorting(objects, options)

The “building” field is defined as a PointField in models.py.

Then in the URL for the resource, append the following, for example:

&latitude=-88.1905699999999939&longitude=40.0913469999999990

This will return all objects within 500 meters.

👤Twitch

Leave a comment