批量计算OD带之间距离 - 基于高德地图API的Python程序
使用Python批量计算OD带之间距离(基于高德地图API)
本程序使用Python实现,可以将带有OD坐标点经纬度的Excel文件导入程序,并批量计算各OD带之间的距离。经纬度数据基于高德坐标系。
所需库:
- pandas
- requests
- json
步骤:
-
导入Excel文件
使用pandas库中的
read_excel函数将Excel文件读入DataFrame:import pandas as pd data = pd.read_excel('data.xlsx') -
使用高德地图API计算距离
请求URL:
https://restapi.amap.com/v3/distance?key=您的key&origins=经度1,纬度1|经度2,纬度2&destination=经度3,纬度3|经度4,纬度4&type=1&output=jsonkey: 高德地图API的keyorigins: 起点经纬度,格式为'经度1,纬度1|经度2,纬度2',多个起点用'|'分隔destination: 终点经纬度,格式为'经度3,纬度3|经度4,纬度4',多个终点用'|'分隔type: 计算方式,1表示驾车距离output: 输出格式,json
使用requests库向API发送请求,解析返回的json数据获取距离值:
import requests import json def get_distance(origin, destination, key): url = 'https://restapi.amap.com/v3/distance?key={}&origins={},{}&destination={},{}&type=1&output=json'.format(key, origin[1], origin[0], destination[1], destination[0]) response = requests.get(url) result = json.loads(response.text) if result['status'] == '1': distance = result['results'][0]['distance'] else: distance = -1 return distance -
计算所有OD带之间的距离
使用pandas库的
apply函数对每一行数据进行计算,并将结果保存到新的列中:key = '您的key' data['distance'] = data.apply(lambda x: get_distance((x['起点经度'], x['起点纬度']), (x['终点经度'], x['终点纬度']), key), axis=1) data.to_excel('result.xlsx', index=False)
完整代码:
import pandas as pd
import requests
import json
def get_distance(origin, destination, key):
url = 'https://restapi.amap.com/v3/distance?key={}&origins={},{}&destination={},{}&type=1&output=json'.format(key, origin[1], origin[0], destination[1], destination[0])
response = requests.get(url)
result = json.loads(response.text)
if result['status'] == '1':
distance = result['results'][0]['distance']
else:
distance = -1
return distance
key = '您的key'
data = pd.read_excel('data.xlsx')
data['distance'] = data.apply(lambda x: get_distance((x['起点经度'], x['起点纬度']), (x['终点经度'], x['终点纬度']), key), axis=1)
data.to_excel('result.xlsx', index=False)
注意:
- 替换代码中的'您的key'为您的高德地图API key。
- 确保Excel文件中的经纬度列名分别为'起点经度'、'起点纬度'、'终点经度'、'终点纬度'。
- 代码中的
type=1表示计算驾车距离,您可以根据需要更改为其他类型。 - 高德地图API有调用次数限制,请注意使用次数。
- 若程序运行出错,请检查您的代码和网络连接。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/m0KJ 著作权归作者所有。请勿转载和采集!