gpt4 book ai didi

python - 在 Google App Engine 上用 Python 计算城市之间的距离并基于 GeoPT 查找周边城市

转载 作者:太空狗 更新时间:2023-10-30 00:33:24 25 4
gpt4 key购买 nike

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

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

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

最佳答案

这很完美,但是有点慢:

计算距离的函数。传递给此函数的参数是位置或 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

关于python - 在 Google App Engine 上用 Python 计算城市之间的距离并基于 GeoPT 查找周边城市,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10693699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com