利用上一篇得到的城市经纬度算城市距离

 import requests
from math import radians, cos, sin, asin, sqrt def geocode(address):
url= 'http://api.map.baidu.com/geocoder?output=json&key=f247cdb592eb43ebac6ccd27f796e2d2&address='+str(address)
response = requests.get(url)
answer = response.json()
#print(address + "的经纬度:", answer['geocodes'][0]['location'])
if answer['status'] == 'INVALID_PARAMETERS':
return 0,0
else:
lon = float(answer['result']['location']['lng'])
lat = float(answer['result']['location']['lat'])
return lon ,lat
def distence(address1,address2): lon1, lat1 = geocode(address1)
lon2, lat2 = geocode(address2) # 将十进制度数转化为弧度
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # haversine公式
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # 地球平均半径,单位为公里
return int(c * r)
def distence_list(city_array):
distence_array = []
for i in range(a.shape[0]):
distence_array.append(distence(city_array[i][0],city_array[i][1]))
return np.array(distence_array)

Python3 计算城市距离-LMLPHP

05-25 08:10