Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
Distance from what? – Derek Swingley Nov 2 '10 at 21:46

Just change

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


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

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.