问题
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?
回答1:
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)
回答2:
@Tyler's answer is wrong in many ways. The correct code would be:
ne = (latitude, longitude)
sw = (latitude, longitude)
xmin=sw[1]
ymin=sw[0]
xmax=ne[1]
ymax=ne[0]
bbox = (xmin, ymin, xmax, ymax)
from django.contrib.gis.geos import Polygon
geom = Polygon.from_bbox(bbox)
queryset = Place.objects.filter(poly__contained=geom)
来源:https://stackoverflow.com/questions/9466043/geodjango-within-a-ne-sw-box