一、簡介
路徑規划中包括步行、公交、駕車、騎行等不同方式,今天借助高德地圖web服務api,實現出行路線規划。
思路
-
根據地點獲取經緯度
-
根據經緯度調用api獲取路線
-
對路線數據進行處理,便於瀏覽
高德地圖API
對應鏈接
https://lbs.amap.com/api/webservice/guide/api/direction
去高德地圖的開放平台注冊一個賬號,並且創建自己的項目,系統會分配給你一個 key 值。
在開發支持中選擇 web服務,選中 web服務api
二、獲取經緯度
輸入地點、輸出經緯度
def get_location_x_y(place):
#place = input("請輸入您要查詢的地址")
url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
parameters = {
'key':'高德官網獲取key',
'address':'%s' % place
}
page_resource = requests.get(url,params=parameters)
text = page_resource.text #獲得數據是json格式
data = json.loads(text) #把數據變成字典格式
location = data["geocodes"][0]['location']
return location
if __name__ == '__main__':
print(get_location_x_y("北京西站"))
獲取結果
三、路線規划(四種方式)
獲取起點、終點經緯度、出行方式
from_place = input("請輸入起始地址")
from_location = get_location_x_y(from_place)
to_place = input("請輸入目的地")
to_location = get_location_x_y(to_place)
type = input("出行方式(1.公交、2.步行、3.駕車、4.騎行),請輸入數字")
獲取出行路線
type是出行方式(四種方式對應1、2、3、4)
不同的出行方式,高德地圖web服務api鏈接也不同
url="https://restapi.amap.com"
if type=="1":
url = url+ "/v3/direction/transit/integrated"
elif type=="2":
url = url + "/v3/direction/walking"
elif type=="3":
url = url + "/v3/direction/driving"
elif type == "4":
url = url + "/v4/direction/bicycling"
請求參數
parameters = {
'key': '高德官網獲取key',
'origin': str(from_location),
'destination': str(to_location),
'extensions':'all',
'output':'json',
'city':'020',
}
參數中from_location是起點經緯度,to_location是終點經緯度,output是數據返回的格式,這里返回json(官網還給了很多種格式,比如xml等)
數據處理
if type=="1":
txt = txt['route']['transits']
for i in txt:
i = i['segments'][0]['bus']['buslines'][0]['name']
print(i)
elif type=="2":
txt = txt['route']['paths'][0]['steps']
for i in txt:
i = i['instruction']
print(i)
elif type=="3":
txt = txt['route']['paths'][0]['steps']
for i in txt:
i = i['instruction']
print(i)
elif type == "4":
txt = txt['data']['paths'][0]['steps']
for i in txt:
i = i['instruction']
print(i)
根據不同的出行方式,獲取的數據key不一樣,所以需要對應的去處理,便於瀏覽。
四、演示效果
1、公交
2、步行
3、駕車
4、騎行
五、結尾
OK,以上就是python通過借助高德地圖web服務實現不同出行方式的路線規划。完整源碼獲取方式在下方
【本文完整源碼獲取方式】
公眾號回復:高德出行
------------------- End -------------------
【各種爬蟲源碼獲取方式】
識別文末二維碼,回復:爬蟲源碼
python竊取攝像頭照片(攝像頭拍照+郵箱發送+打包exe)
歡迎大家點贊,留言,轉發,轉載,感謝大家的相伴與支持
想加入Python學習群請在后台回復【入群】
萬水千山總是情,點個【在看】行不行
【加群獲取學習資料QQ群:901381280】
【各種爬蟲源碼獲取方式】
識別文末二維碼,回復:爬蟲源碼
歡迎關注公眾號:Python爬蟲數據分析挖掘,方便及時閱讀最新文章
回復【開源源碼】免費獲取更多開源項目源碼