zoukankan      html  css  js  c++  java
  • 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:
    ",distance)
    #     print("duration:
    ",duration)
    #     print("steps:
    ",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 {
                 100%;
                height: 95%;
            }
            #panel {
                position: fixed;
                background-color: white;
                max-height: 90%;
                overflow-y: auto;
                top: 10px;
                right: 10px;
                 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=" 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=" 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>
    

    结尾:

    高德地图入门非常简单,官方把文档写的非常好,看官方好多问题都能解决。

  • 相关阅读:
    链表总结
    源码,反码,补码,位运算
    JAVA打印乘法口诀表
    JAVA打印空三角形
    JAVA打印三角形
    列表,元组,字典,集合类型
    for 循环 ,数字类型,以及字符串类型
    基本运算符补充,流程控制if判断与while循环
    内存管理,数据类型的基本使用与基本运算符(python2中与用户交互)
    编程的分类,以及运行python解释器的原理,最后变量
  • 原文地址:https://www.cnblogs.com/yangxiao-/p/14585450.html
Copyright © 2011-2022 走看看