博主你好,感谢你关于百度地图api的分享,我这两天在根据你提供的代码进行OD点出行获取时,pycharm提示coor没有被定义,想请教一下你应该如何修改,感谢!
# -*- coding: utf-8 -*-
# @Author: Xie
# @Date: 2021-04-15 11:49:25
# @Last Modified by: Xie
# @Last Modified time: 2021-04-15 11:58:10
import requests
import json
import time
starttime=time.asctime(time.localtime(time.time()))
starttime1=time.time()
# 调用百度API进行两点之间的路径查询
def getjson(ocoo,dcoo):
# 先纬度后经度
url='http://api.map.baidu.com/direction/v2/driving?origin='+ocoo+'&destination='+dcoo+'&coord_type=wgs84&departure_time=1595548800&tactics_incity=4&ak=bIZGKoUuxipmIGGMx5kOttQTqZ44pWNT'
while True:
try:
response=requests.get(url=url,timeout=5)
break
except requests.exceptions.ConnectionError:
print ('ConnectionError -- please wait 3 sec')
time.sleep(3)
except requests.exceptions.ChunkedEncodingError:
print ('ChunkedEncodingError -- please wait 3 sec')
time.sleep(3)
except:
print ('Unknow error')
time.sleep(3)
html=response.text
decodejson=json.loads(html)
return decodejson
# 输入查询文件的路径
file_object=open(r'D:\个人文件\pythonProject1\venv\demo.csv','r',encoding='UTF-8')
# 输入结果文件的保存路径
file_object2=open(r'D:\个人文件\pythonProject1\venv\demo_end.csv','w')
count=0
try:
for line in file_object:
count=count+1
#print coor
decodejson=getjson(coor,door)
if decodejson.get('status')==0:#表示运行成功
result=decodejson.get('result')
routes=result.get('routes')
#获得需要的时间和距离
if len(routes)>0:
time2=routes[0].get('duration')
distance=routes[0].get('distance')
file_object2.write(str(idn)+','+str(time2)+','+str(distance) +'\n')
if count%10==0:
finishtime=time.asctime( time.localtime(time.time()))
finishtime1=time.time()
print (count)
print ('duration:',(finishtime1-starttime1)/60.0,'mins')
else:
print (str(coor)+','+ str(decodejson.get('status'))+decodejson.get('message'))
finally:
file_object.close()
file_object2.close()
print ('finish')
csv文件
前面的“def getjson(ocoo,dcoo):”和后面的“decodejson=getjson(coor,door)”变量不一致,调整为相同的名称后依旧显示为“not define”,尝试将excel表格(文章里的格式)换成三列,分别为“id”、“coor”和“door”也无法实现
希望可以正常运行代码,感谢!