[GIS] GeoDjango: order PointField by distance

geodjango

I've got a GeoDjango model as follows:

class City(models.Model):
    id = models.IntegerField(primary_key=True) 
    county = models.ForeignKey(County)
    location = models.PointField(null=True, blank=True)

How do I get all the cities within a particular bounding box, ordered by distance? I've got the relevant latlngs as strings, but I'm not really sure how to construct the bounding box, or the central point, or the query 🙂

EDITED: have now worked out how to construct the bounding box and get places – but can anyone help me sort by distance?

swLat = request.GET.get('swLat')
swLng = request.GET.get('swLng')
neLat = request.GET.get('neLat')
neLng = request.GET.get('neLng')
centreLat = request.GET.get('centreLat')
centreLng = request.GET.get('centreLng')
centre = fromstr('POINT(%s %s)' % (centreLat, centreLng))
boundaries = fromstr('POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \
       (swLng, swLat, swLng, neLat, neLng, neLat, neLng, swLat, swLng, swLat))
cities = City.objects.filter(location__within=boundaries)
# how to order cities by distance from centre?

Thanks for helping out a beginner!

Best Answer

Just change

cities = City.objects.filter(location__within=boundaries)

To

cities = City.objects.filter(location__within=boundaries).distance(centre).order_by('distance')

Each City object will also have a 'distance' attribute.