1. 程式人生 > 其它 >Python呼叫百度地圖api獲取起點終點距離和預估時長

Python呼叫百度地圖api獲取起點終點距離和預估時長

去百度地圖開放平臺申請API的AK

https://lbsyun.baidu.com/apiconsole/center#/home

import pandas as pd
import requests, json

AK = "xxxx"


# 獲取位置
def getPosition(address):
    url = r"http://api.map.baidu.com/place/v2/search?query={}&region=全國&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