I'm creating a geo app with Google Maps and I receive bounding box as 2 coordinates:
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With