web頁面采用高德地圖JS api和Web api實現路徑規划


引言

這幾天參加經管三創杯比賽,要做一個物流的網頁,要求實現路徑規划。第一個想到的就是高德地圖(不喜歡百度地圖,感覺坑)。

整體的想法就是通過輸入起始點和終止點,返回最優路徑規划。

運行效果

工具

  • python3.8

  • flask框架

  • 高德地圖API

內容

不管說什么先去官方文檔看看,在這里我只舉列騎行路徑規划,其他的類似。

通過看代碼我們發現,最后需要的是兩個點的經緯度坐標,而高德地圖也給我們准備好提供經緯度的方法了。方法

具體步驟如下

  • 第一步,申請”Web服務API”密鑰(Key);

  • 第二步,拼接HTTP請求URL,第一步申請的Key需作為必填參數一同發送;

  • 第三步,接收HTTP請求返回的數據(JSON或XML格式),解析數據。

如無特殊聲明,接口的輸入參數和輸出數據編碼全部統一為UTF-8。

重要一點的是申請api時候,需要申請倆個api,如下圖。一個用來畫圖,一個用來返回我們需要的經緯度值

代碼

獲取經緯度api代碼

from flask import Flask,render_template,request

import requests
app = Flask(__name__)


@app.route('/')
def hello_world():
    address = []
    return render_template('route.html',address=address,origin_str="",destination_str="")

## 獲取輸入地址的經緯度
@app.route('/get_geo',methods=["POST"])
def get_geo():
    info = request.form.to_dict()
    origin_str = info.get("origin_str")
    destination_str = info.get("destination_str")
    parameters = {
        "key":"你申請的web服務key值",
        "address":origin_str+"|"+destination_str,
        "batch":True, #批量查詢操作,最多支持 10 個地址進行批量查詢。
    }
    response = requests.get("https://restapi.amap.com/v3/geocode/geo?parameters",params=parameters)
    data = response.json()["geocodes"]
    origin = [float(value) for value in data[0]["location"].split(",")]
    destination = [float(value) for value in data[1]["location"].split(",")]
    #get_best_route(origin,destination)
    address = [origin,destination]
    print(address)
    return render_template('route.html',address=address,origin_str=origin_str,destination_str=destination_str)
## 返回路線規划
# def get_best_route(origin,destination):
#     parameters = {
#         "key": "eca4b61cc086d41e12013c35dc12c3ce",
#         "origin":origin,
#         "destination":destination,
#     }
#     response = requests.get("https://restapi.amap.com/v4/direction/bicycling?parameters",params=parameters)
#     data = response.json()["data"]["paths"][0]
#     distance = data["distance"]
#     duration = data["duration"]
#     steps = data["steps"]
#     print("distance:\n",distance)
#     print("duration:\n",duration)
#     print("steps:\n",steps)


if __name__ == '__main__':

    app.run()

首頁頁面

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>位置經緯度 + 騎行路線規划</title>
    <style type="text/css">
        html,
        body,
        #container {
            width: 100%;
            height: 95%;
        }
        #panel {
            position: fixed;
            background-color: white;
            max-height: 90%;
            overflow-y: auto;
            top: 10px;
            right: 10px;
            width: 280px;
        }
        #panel .amap-lib-driving {
            border-radius: 4px;
            overflow: hidden;
        }
    </style>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <script type="text/javascript" src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你申請的js的key值&plugin=AMap.Riding"></script>
    <script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div style="height: 20%">
    <form action="/get_geo" style="width: 100%" METHOD="post">
        <input type="text" placeholder="起始位置:例如:北京市朝陽區阜通東大街6號" name="origin_str" class="form-group" width="500px" value="{{ origin_str }}">
        <input type="text" placeholder="終止位置:例如:上海市黃浦區人民大道200號" name="destination_str" class="form-group" value="{{ destination_str }}" width="500px">
        <input type="submit" value="查詢" class="btn btn-success" style="width: 150px;height: 40px;font-size: 20px" >
    </form>
</div>
<div id="container"></div>
<div id="panel"></div>
<script type="text/javascript">
    var map = new AMap.Map("container", {
        resizeEnable: true,
        center: [116.397428, 39.90923],//地圖中心點
        zoom: 13 //地圖顯示的縮放級別
    });
    //騎行導航
       var riding = new AMap.Riding({
            map: map,
            panel: "panel"
        });
    //根據起終點坐標規划騎行路線
    {% if address!= None %}
        riding.search({{ address[0] }},{{ address[1] }}, function(status, result) {
        // result即是對應的騎行路線數據信息,相關數據結構文檔請參考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_RidingResult
        if (status === 'complete') {
            log.success('繪制騎行路線完成')
        } else {
            log.error('騎行路線數據查詢失敗' + result)
        }
    });
    {% endif %}

</script>
</body>
</html>

結尾:

高德地圖入門非常簡單,官方把文檔寫的非常好,看官方好多問題都能解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM