python计算两个地址之间的距离

我们调用高德地图的API来计算经纬度

#计算地址经纬度
import requests

def geocode(address):
    parameters = {'address': address, 'key': 'cb649a25c1f81c1451adbeca73623251'}
    base = 'http://restapi.amap.com/v3/geocode/geo'
    response = requests.get(base, parameters)
    answer = response.json()
    print(address + "的经纬度:", answer['geocodes'][0]['location'])

   lon = float(answer['geocodes'][0]['location'].split(',')[0])
   lat = float(answer['geocodes'][0]['location'].split(',')[1])
geocode(address)    

我们输入下面两个地址,得到相应的经纬度。

address1 =’上海市徐汇区桂箐路靠近华鑫天地’
address2 =’上海市徐汇区田林路200号华鑫天地C座3楼’

上海市徐汇区桂箐路靠近华鑫天地的经纬度: 121.407124,31.169677
上海市浦东新区张江高科技园的经纬度: 121.593357,31.214343
lon1 = 121.407124
lat1 = 31.169677
lon2 = 121.593357
lat2 =31.214343
#计算距离 
from math import radians, cos, sin, asin, sqrt  

# 将十进制度数转化为弧度  
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 c * r * 1000  

最终结果如下,两个地方之间的距离约18公里

c * r * 1000 
Out[58]: 18397.59615786144

你可能感兴趣的:(python)