写一个程序将带有OD坐标点经纬度的excel文件导入程序可批量计算OD带之间的距离经纬度数据基于高德坐标系
(以下代码使用Python实现,需要安装pandas、requests、json库)
首先需要将excel文件读入程序,可以使用pandas库中的read_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=json
其中,key为高德地图API的key,origins为起点经纬度,destination为终点经纬度,type为计算方式,output为输出格式。
可以使用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
最后,可以使用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)
原文地址: https://www.cveoy.top/t/topic/bwQL 著作权归作者所有。请勿转载和采集!