1

我无法弄清楚如何进行边界框查询以查找包含在由(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

背景资料:

  • 数据库后端:Postgresql-8.4 & PostGIS 1.5.8
  • Django 1.4.3
  • 操作系统:Ubuntu 12.04x32

任何帮助将非常感激。

谢谢大家,马特

4

1 回答 1

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')
于 2013-03-09T22:14:57.877 回答