使用Google App Engine上的Python,根据GeoPT计算城市之间的距离并查找周边城市

Amy*_*yth 5 python google-app-engine distance geolocation

我定义了一个城市模型,用于保存城市geoname_idlocation(如GeoPt)城市.我想要实现两件事.

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

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

Amy*_*yth 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
Run Code Online (Sandbox Code Playgroud)

用于计算半径内的周边城市的函数.这是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
Run Code Online (Sandbox Code Playgroud)