Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeoDjango within a NE, SW box

I'm creating a geo app with Google Maps and I receive bounding box as 2 coordinates:

  • north east
  • south west

I have a model with PointField.

from django.contrib.gis.db import models

class Place(models.Model):
    name            = models.CharField(max_length=200)
    address         = models.CharField(max_length=200)

    location        = models.PointField()

How could I perform a query to get all places within bounding box?

like image 577
FrEaKmAn Avatar asked Feb 27 '12 13:02

FrEaKmAn


1 Answers

Assuming that the "2 coordinates" are x,y tuples, for example:

ne = (50.0, -90)
sw = (45.5, -95)

You can extract the coordinates and create a bounding box tuple:

xmin = sw[0]
ymin = ne[1]
xmax = sw[1]
ymax = ne[0]
bbox = (xmin, ymin, xmax, ymax)

Using the bounding box geometry, query your Place records using a spatial lookup:

from django.contrib.gis.geos import Polygon

geom = Polygon.from_bbox(bbox)
queryset = Place.objects.filter(poly__contained=geom)
like image 145
Tyler Erickson Avatar answered Oct 17 '22 19:10

Tyler Erickson