您的位置:首页 > 编程语言 > Python开发

Python3 计算城市距离

2017-07-20 10:46 176 查看
利用上一篇得到的城市经纬度算城市距离

1 def geocode(address):
2     url= 'http://api.map.baidu.com/geocoder?output=json&key=f247cdb592eb43ebac6ccd27f796e2d2&address='+str(address)
3     response = requests.get(url)
4     answer = response.json()
5     #print(address + "的经纬度:", answer['geocodes'][0]['location'])
6     if answer['status']  == 'INVALID_PARAMETERS':
7         return 0,0
8     else:
9         lon = float(answer['result']['location']['lng'])
10         lat = float(answer['result']['location']['lat'])
11         return lon ,lat
12 def distence(address1,address2):
13
14     lon1, lat1 = geocode(address1)
15     lon2, lat2 = geocode(address2)
16
17     #计算距离
18     from math import radians, cos, sin, asin, sqrt
19
20     # 将十进制度数转化为弧度
21     lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
22
23     # haversine公式
24     dlon = lon2 - lon1
25     dlat = lat2 - lat1
26     a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
27     c = 2 * asin(sqrt(a))
28     r = 6371 # 地球平均半径,单位为公里
29     return int(c * r)
30 def distence_list(city_array):
31     distence_array = []
32     for i in range(a.shape[0]):
33         distence_array.append(distence(city_array[i][0],city_array[i][1]))
34     return np.array(distence_array)


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: