5

我定义了一个城市模型,它保存了一个城市的geoname_idlocation(作为GeoPt)。我想实现两件事。

  1. 我想500km从给定城市获取半径范围内的所有城市。
  2. 我想计算km两个给定城市之间的距离。

实现这一目标的最佳方法是什么,请记住我有一个非常大的城市数据库,我不想在性能因素上牺牲太多。任何帮助或建议表示赞赏。

4

3 回答 3

7

这很完美,但速度有点慢:

计算距离的函数。传递给此函数的参数是位置或 Geopt() 的纬度和经度元组:

def HaversineDistance(location1, location2):
  """Method to calculate Distance between two sets of Lat/Lon."""
  lat1, lon1 = location1
  lat2, lon2 = location2
  earth = 6371 #Earth's Radius in Kms.

 #Calculate Distance based in Haversine Formula
 dlat = math.radians(lat2-lat1)
 dlon = math.radians(lon2-lon1)
 a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
 d = earth * c
 return d

计算半径内的周边城市的功能。这是存储所有城市的 City 模型下的方法:

def get_closest_cities(self, kms):
  cities = []
  #Find surrounding Cities of a given city within a given radius
  allcities = self.country.city_set
  for city in allcities:
    distance = HaversineDistance((self.location.lat, self.location.lon),(city.location.lat, city.location.lon))
    if not distance >= kms:
      cities.append((city.name, int(distance)))
  cities.remove(cities[0])
  return cities
于 2012-05-22T20:53:30.957 回答
3

Google App Engine 不支持地理空间查询,但您可以参考Geospatial Queries with Google App Engine using GeoModel

您可能还想考虑使用mongoDB支持地理空间索引的其他数据库,并可能将其作为仅执行此操作的外部服务。

于 2012-05-22T00:00:24.750 回答
2
  1. 您可以使用类似于https://developers.google.com/appengine/articles/geosearch的内容
  2. 只需加载两个城市的位置并使用三角函数来计算距离。参见例如http://www.movable-type.co.uk/scripts/latlong.html
于 2012-05-21T23:05:23.683 回答