我无法弄清楚如何进行边界框查询以查找(swLat,swLon,neLat,neLon)指定的边界框中包含的所有UserProfile对象。尽管将点设置为在边界框内居中,但仍返回一个空数组。下面是我的模型和查询代码。
from django.contrib.gis.db import models
from django.contrib.gis.geos import GEOSGeometry
class UserProfile(models.Model):
location = models.PointField(srid=4326, blank=True, null=True)
objects = models.GeoManager()
def setLocation(self, lat, lon):
if not self.location:
self.location = GEOSGeometry('POINT(%s %s)' % (lat, lon))
else:
self.location.set_x(float(lat))
self.location.set_y(float(lon))
self.save()
from models import UserProfile
from django.contrib.gis.geos import Polygon
class SomeView:
def getUserProfilesWithinBBox(swMapBoundsLat, swMapBoundsLon, neMapBoundsLat, neMapBoundsLon, userProfileLocationLat, userProfileLocationLon, userProfile):
'''neMapBoundsLat=38.908254,neMapBoundsLon=-77.002034
swMapBoundsLat=38.888515,seMapBoundsLon-77.070698
userProfileLocationLat=38.89838500999149, userProfileLocationLon=-77.03636580000001
'''
userProfile.setLocation(userProfileLat, userProfileLon)
geom = Polygon.from_bbox((swMapBoundsLat, swMapBoundsLon, neMapBoundsLat, neMapBoundsLon))
matchingUserProfiles = UserProfile.objects.filter(location__bbcontains=geom)
# matchingUserProfiles should contain the userProfile that was just saved, but is always an empty list. what am I doing wrong?
return matchingUserProfiles
背景资料:
非常感谢任何帮助。
谢谢你们, 马特
答案 0 :(得分:0)
如果您希望按配置文件与边界框中心的距离对其进行排序。
center = Point(float(lat), float(lng)) # lat/lng of the center of the bounding box
geo_query = Q(point__within=geom)
UserProfile.objects.filter(geo_query).distance(center).order_by('distance')