GeoDjango within a NE, SW box

℡╲_俬逩灬. 提交于 2019-12-06 21:06:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!