在Google App Engine上使用Python计算城市之间的距离并基于GeoPT查找周围的城市。

5
我有一个城市模型定义,保存了一个城市的geoname_idlocation(作为GeoPt)。我想实现两件事:
  1. 我想获取给定城市500km半径内的所有城市。
  2. 我想计算两个给定城市之间的距离(单位:km)。
在保持性能的同时,如何最好地实现这些功能,考虑到我有一个非常大的城市数据库?任何帮助或建议都将不胜感激。
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

3

我不想为此使用单独的库,因为我已经将城市的纬度和经度保存在数据存储中。你认为简单的计算就可以吗?或者你建议使用geomodel?这会如何影响应用程序的性能?感谢您的回复。 :) - Amyth
除非你要实现自己的地理空间索引,否则没有其他办法。因为GAE不支持它。你应该至少尝试一下GeoModel。性能取决于数据存储的大小,并且肯定会增加你的索引大小。阅读文档以了解它们是如何实现它的。 - Lipis
谢谢,Lipis,我现在会看一遍! - Amyth

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接