路径规划API是一套以HTTP形式提供的步行、公交、驾车查询及行驶距离计算接口,返回JSON 或 XML格式的查询数据,用于实现路径规划功能的开发
import requests
import json
from pymongo import MongoClient
import time
client = MongoClient('localhost',27017)
db = client.Route_planning
collection = db.table_3
origin_list = list()
destination_list = list()
with open("origin.txt", 'r', encoding='UTF-8') as txt_file:
for each_line in txt_file:
if each_line != "" and each_line != "\n":
fields = each_line.split("\n")
origin = fields[0]
origin_list.append(origin)
txt_file.close()
with open("destination.txt", 'r', encoding='UTF-8') as txt_file:
for each_line in txt_file:
if each_line != "" and each_line != "\n":
fields = each_line.split("\n")
destination = fields[0]
destination_list.append(destination)
txt_file.close()
def getjson(origin,destination):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
}
pa = {
'key': 'xxxxxxxxxxxxxxx', #从控制台申请
'origin': origin,
'destination':destination,
'output': 'JSON'
}
r = requests.get('https://restapi.amap.com/v3/direction/driving?', params=pa, headers=headers)
decodejson = json.loads(r.text)
return decodejson
for a in origin_list:
for b in destination_list:
decodejson = getjson(a,b)
print(decodejson)
if decodejson['route']:
try:
origin = decodejson['route']['origin'] #起点
except:
origin = None
try:
destination = decodejson['route']['destination'] #终点
except:
destination = None
if decodejson['route']['paths']:
for eachone in decodejson['route']['paths']:
try:
distance = eachone['distance'] #行驶距离
except:
distance = None
try:
duration = eachone['duration'] #预计行驶时间,单位:秒
except:
duration = None
try:
strategy = eachone['strategy'] #导航策略
except:
strategy = None
data = {'origin': origin, 'destination': destination, 'distance': distance, 'duration': duration,'strategy':strategy}
collection.insert_one(data)
time.sleep(0.2)
origin.txt 如下:
destination.txt 如下:
最终结果如下:
谢谢浏览 !