Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

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
1  
Distance from what? –  Derek Swingley Nov 2 '10 at 21:46
add comment

1 Answer 1

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.

share|improve this answer
add comment

Your Answer

 
discard

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