【问题标题】:GeoDjango bounding box filter usageGeoDjango 边界框过滤器使用
【发布时间】:2013-01-20 17:50:38
【问题描述】:

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

任何帮助将不胜感激。

谢谢各位, 马特

【问题讨论】:

  • 没关系,弄明白了。我需要使用'within',因为我想查看该点是否在边界框内,而不是边界框是否在该点内(duh!:P)matchingUserProfiles = UserProfile.objects.filter(location__within=geom)跨度>

标签: django postgis geodjango


【解决方案1】:

如果您想按与边界框中心的接近程度对配置文件进行排序。

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')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    相关资源
    最近更新 更多