去百度地图开放平台申请API的AK
import pandas as pd
import requests, json
AK = "xxxx"
# 获取位置
def getPosition(address):
url = r"http://api.map.baidu.com/place/v2/search?query={}®ion=全国&output=json&ak={}".format(
address,
AK
)
res = requests.get(url)
json_data = json.loads(res.text)
if json_data["status"] == 0:
lat = json_data["results"][0]["location"]["lat"] # 纬度
lng = json_data["results"][0]["location"]["lng"] # 经度
else:
print(json_data["message"])
return "0,0", json_data["status"]
return str(lat) + "," + str(lng), json_data["status"]
# 获取距离
def getDistance(start, end):
url = "https://api.map.baidu.com/directionlite/v1/driving?origin={}&destination={}&ak={}".format(
start,
end,
AK
)
res = requests.get(url)
json_data = json.loads(res.text)
if json_data["status"] == 0:
return json_data["result"]["routes"][0]["distance"]
else:
print(json_data["message"])
return -1
# 计算距离
def calcDistance(startName, endName):
start, status1 = getPosition(startName)
end, status2 = getPosition(endName)
if status1 == 0 and status2 == 0:
return getDistance(start, end)
else:
return -1
# 计算时长
def calcDuration(startName, endName):
start, status1 = getPosition(startName)
end, status2 = getPosition(endName)
if status1 == 0 and status2 == 0:
return round(getTime(start, end) / 60, 1) # 将时间转换为分钟
else:
return -1
# 获取两地开车的时间
def getTime(start, end):
url = "https://api.map.baidu.com/directionlite/v1/driving?origin={}&destination={}&ak={}".format(
start, end, AK
)
res = requests.get(url)
json_data = json.loads(res.text)
if json_data["status"] == 0:
# return json_data["result"]["routes"][0]["distance"] # 获取距离
return int(json_data['result']['routes'][0]['duration']) # 获取时间,单位s
else:
print(json_data["message"])
return -1
if __name__ == "__main__":
data = pd.read_excel("data.xlsx")
res = []
for i in range(len(data)):
startName = data.iloc[i, 0]
endName = data.iloc[i, 1]
kilometre = calcDistance(startName, endName)
duration = calcDuration(startName, endName)
# 以千米为单位
res.append([startName, endName, kilometre / 1000, duration])
pd.DataFrame(res).to_excel(
"result.xlsx",
header=["起点", "终点", "公里", "驾驶时长"],
index=None,
encoding="utf-8"
)
data.xlsx内容
起点 | 终占 |
---|---|
北京市xxx | 北京市朝阳区xxx |
输出结果: result.xlsx
起点 | 终点 | 公里 | 驾驶时长 |
---|---|---|---|
北京市xxx | 北京市朝阳区xxx | 2.888 | 12.3 |