2013-03-05 142 views
0

在我建设的网站中,我用城市的外键存储了事件。就像这样:有必要使用GeoDjango来查询Django中的距离吗?

class Event(models.Model): 
    name = models.CharField(max_length=255) 
    ... 
    ciudad = models.ForeignKey(City) 

class City(models.Model): 
    name = models.CharField(max_length=500) 
    ... 
    lat = models.FloatField() 
    lon = models.FloatField() 

我想在一些城市一些公里到查询事件。 我实际上做的是:

# isInRange takes two cities and a distance in kms and calculates 
# if the distance between the cities (by the fields lat and lon and 
# one nice formula) is minor than the given distance. 
results = [] 
for event in Event.objects.all(): 
    if isInRange(city, event.city, kms): 
     results.append(event) 

我知道,是非常低效的。我知道GeoDjango可以做到这一点,但这是我在整个项目中必须做的唯一“地理事物”。我必须毫无理由地使用那种“复杂”的解决方案,或者有办法以更高效的方式来做到这一点?

回答

8

如果你不需要在你的范围内非常确切,你可以使用近似值来计算经度和纬度范围。概念解释here

使用城市位置和距离,查找纬度变化(无论在哪里都保持不变),并且经度的近似变化(根据纬度变化)。然后计算一个边界框。

import math 

# earth_radius = 3960.0 # for miles 
earth_radius = 6371.0 # for kms 
degrees_to_radians = math.pi/180.0 
radians_to_degrees = 180.0/math.pi 

def change_in_latitude(distance): 
    "Given a distance north, return the change in latitude." 
    return (distance/earth_radius)*radians_to_degrees 

def change_in_longitude(latitude, distance): 
    "Given a latitude and a distance west, return the change in longitude." 
    # Find the radius of a circle around the earth at given latitude. 
    r = earth_radius*math.cos(latitude*degrees_to_radians) 
    return (distance/r)*radians_to_degrees 

def bounding_box(latitude, longitude, distance): 
    lat_change = change_in_latitude(distance) 
    lat_max = latitude + lat_change 
    lat_min = latitude - lat_change 
    lon_change = change_in_longitude(latitude, distance) 
    lon_max = longitude + lon_change 
    lon_min = longitude - lon_change 
    return (lon_max, lon_min, lat_max, lat_min) 

要距离kms内计算事件的city

lon_max, lon_min, lat_max, lat_min = bounding_box(city.lat, city.lon, kms) 
events = Event.objects.filter(
    city__lat__lte=lat_max, 
    city__lat__gte=lat_min, 
    city__lon__lte=lon_max, 
    city__lon__gte=lon_min 
) 

请记住,误差变大的距离越大,越接近你是两极。反经络(国际日期线)附近的地方也存在问题,但很容易检查(检查经度是否> 180或< -180)。

如果你想得到更多的acurate结果,你可以使用这个方法作为第一遍,然后使用你的函数,所以你不必单独通过每个事件。

+0

很好的答案!我明白错误的事情。这是因为距离应该是一个圆形,这会计算一个伪矩形,不是吗?无论如何,我会使用这种方法。如果我注意到错误太多,我将切换到GeoDjango。再次,很好的回答和谢谢! – sanfilippopablo 2013-03-05 18:02:18