Python通过高德地图API批量计算两地路线距离

  • Post author:
  • Post category:python


公司需求批量计算两地之间行车距离,故此记录一下,数据接口采用高德地图开发者api,需要注册,注册后免费版的数据量已够满足大多数使用。

import pandas as pd
import requests
import json

AK = "*******"  #你自己的注册码。

def getLocation(address):
    url = f"https://restapi.amap.com/v3/geocode/geo?address={address}&output=json&key={AK}"      #高德地图
    res = requests.get(url)
    json_data = json.loads(res.text)

    if json_data["status"] == "1":        # 成功时返回1
        lnglat = json_data["geocodes"][0]["location"]
    else:
        return "no data", json_data["status"]
    return lnglat, json_data["status"]

def getDistance(start, end):
    url = f"https://restapi.amap.com/v3/direction/driving?origin={start}&destination={end}&output=json&key={AK}"
    res = requests.get(url)
    json_data = json.loads(res.text)

    if json_data["status"] == "1":
        return json_data["route"]["paths"][0]["distance"]
    else:
        return -1

def calDistance(startAddr, endAddr):
    start, status1 = getLocation(startAddr)
    end, status2 = getLocation(endAddr)

    if status1 == "1" and status2 == "1":
        return getDistance(start, end)
    else:
        return -1

if __name__ == "__main__":
    data = pd.read_excel("bj.xlsx")
    result = []
    for i in range(0, len(data)):        
        startAddr = data.iloc[i,0]
        endAddr = data.iloc[i,1]
        dist = int(calDistance(startAddr, endAddr))
        result.append([startAddr, endAddr, dist/1000])
    pd.DataFrame(result).to_excel(
        "result.xlsx",
        header=["出发地", "目的地", "距离"],
        encoding="utf-8"
    )



版权声明:本文为weixin_45249324原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。