WithCoderWithCoderWithCoder

百度地图路书轨迹回放

    因为项目需要,使用到了百度的路书功能。本文介绍路书功能的实现步骤,以备后面使用。

    参考(百度开源库):

    http://lbsyun.baidu.com/index.php?title=jspopular3.0/openlibrary

    基本思路:

    1. 首先生成GPS轨迹点(百度demo使用驾车导航搜索生成路线轨迹点)

    2. 初始化路书对象,将生成的GPS轨迹点传入此对象

    3. 调用对应的接口方法,让小车按着规定好的轨迹运动

    实现:

    1. 首先在页面引入相关js(注意配置好自己的百度地图开发密钥)

    <script src="http://api.map.baidu.com/api?v=2.0&ak=百度地图密钥"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/LuShu/1.2/src/LuShu_min.js"></script>

    2. 生成GPS轨迹点并绘制路线(使用驾车导航路线生成轨迹点)   

        // 实例化一个驾车导航用来生成路线
        var drv = new BMap.DrivingRoute('北京', {
            onSearchComplete: function(res) {
                if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
                    var plan = res.getPlan(0);
                    // 根据搜索结果,生成路径轨迹点
                    var arrPois = [];
                    for (var j = 0j < plan.getNumRoutes(); j++) {
                        var route = plan.getRoute(j);
                        arrPois = arrPois.concat(route.getPath());
                    }

                    // 画轨迹
                    map.addOverlay(new BMap.Polyline(arrPois, { strokeColor: '#111' }));
                    map.setViewport(arrPois);
                }
            }
        });
        var start = new BMap.Point(116.40484439.911836);
        var end = new BMap.Point(116.30810240.056057);
        drv.search(startend);

    3. 重写路书的move函数(需求不一样,可根据需要修改),代码参考文末全部代码

    4. 初始化路书对象

    // 创建路书
    lushu = new BMapLib.LuShu(maparrPois, {
        defaultContent: "",//"从天安门到百度大厦"
        autoView: true,//是否开启自动视野调整,如果开启那么路书在运动过程中会根据视野自动调整
        icon: new BMap.Icon('./images/car.png'new BMap.Size(5226), { anchor: new BMap.Size(2713) }),
        speed: 4500,
        enableRotation: true,//是否设置marker随着道路的走向进行旋转
        landmarkPois: [
            { lng: 116.314782lat: 39.913508html: '加油站'pauseTime: 2 },
            { lng: 116.315391lat: 39.964429html: '高速公路收费<div><img src="//map.baidu.com/img/logo-map.gif"/></div>'pauseTime: 3 },
            { lng: 116.381476lat: 39.974073html: '肯德基早餐'pauseTime: 2 }
        ]
    });

    5. 绑定按钮事件,调用路书的lushu.start()开始,lushu.stop()停止,lushu.pause()暂停等功能

    运行结果:

    1-200414132416207.png

    完整代码:

    

<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>路书</title>
    <style type="text/css">
        body,
        html {
            width100%;
            height100%;
            margin0;
            font-family"微软雅黑";
        }

        #map_canvas {
            width100%;
            height500px;
        }
    </style>
    <script src="http://api.map.baidu.com/api?v=2.0&ak=百度地图密钥"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/LuShu/1.2/src/LuShu_min.js"></script>
</head>

<body>
    <div id="map_canvas"></div>
    <div id="table"></div>
    <button id="run">开始</button>
    <button id="stop">停止</button>
    <button id="pause">暂停</button>
    <button id="hide">隐藏信息窗口</button>
    <button id="show">展示信息窗口</button>
    <script>
        var map = new BMap.Map('map_canvas');
        map.enableScrollWheelZoom();
        map.centerAndZoom(new BMap.Point(116.40439.915), 13);
        var lushu;
        // 实例化一个驾车导航用来生成路线
        var drv = new BMap.DrivingRoute('北京', {
            onSearchComplete: function(res) {
                if (drv.getStatus() == BMAP_STATUS_SUCCESS) {
                    var plan = res.getPlan(0);
                    // 根据搜索结果,生成路径轨迹点
                    var arrPois = [];
                    for (var j = 0j < plan.getNumRoutes(); j++) {
                        var route = plan.getRoute(j);
                        arrPois = arrPois.concat(route.getPath());
                    }

                    // 画轨迹
                    map.addOverlay(new BMap.Polyline(arrPois, { strokeColor: '#111' }));
                    map.setViewport(arrPois);

                    BMapLib.LuShu.prototype._move = function(initPostargetPoseffect) {
                        var pointsArr = [initPostargetPos]; //点数组
                        var me = this,
                            //当前的帧数
                            currentCount = 0,
                            //步长,米/秒
                            timer = 10,
                            step = this._opts.speed / (1000 / timer),
                            //初始坐标
                            init_pos = this._projection.lngLatToPoint(initPos),
                            //获取结束点的(x,y)坐标
                            target_pos = this._projection.lngLatToPoint(targetPos),
                            //总的步长
                            count = Math.round(me._getDistance(init_postarget_pos) / step);
                        //显示折线
                        //如果想显示小车走过的痕迹,放开这段代码就行
                        // this._map.addOverlay(
                        //     new BMap.Polyline(pointsArr, {
                        //         strokeColor: "#00f",
                        //         strokeWeight: 5,
                        //         strokeOpacity: 0.5
                        //     })
                        // ); // 画线

                        //如果小于1直接移动到下一点
                        if (count < 1) {
                            me._moveNext(++me.i);
                            return;
                        }
                        me._intervalFlag = setInterval(function() {
                            //两点之间当前帧数大于总帧数的时候,则说明已经完成移动
                            if (currentCount >= count) {
                                clearInterval(me._intervalFlag);
                                //移动的点已经超过总的长度
                                if (me.i > me._path.length) {
                                    return;
                                }
                                //运行下一个点
                                me._moveNext(++me.i);
                            } else {
                                currentCount++;
                                var x = effect(init_pos.xtarget_pos.xcurrentCountcount),
                                    y = effect(init_pos.ytarget_pos.ycurrentCountcount),
                                    pos = me._projection.pointToLngLat(new BMap.Pixel(xy));
                                //设置marker
                                if (currentCount == 1) {
                                    var proPos = null;
                                    if (me.i - 1 >= 0) {
                                        proPos = me._path[me.i - 1];
                                    }
                                    if (me._opts.enableRotation) {
                                        me.setRotation(proPosinitPostargetPos);
                                    }
                                    if (me._opts.autoView) {
                                        if (!me._map.getBounds().containsPoint(pos)) {
                                            me._map.setCenter(pos);
                                        }
                                    }
                                }
                                //正在移动
                                me._marker.setPosition(pos);
                                //设置自定义overlay的位置
                                me._setInfoWin(pos);
                            }
                        }, timer);
                    };

                    // 创建路书
                    lushu = new BMapLib.LuShu(maparrPois, {
                        defaultContent: "",//"从天安门到百度大厦"
                        autoView: true,//是否开启自动视野调整,如果开启那么路书在运动过程中会根据视野自动调整
                        icon: new BMap.Icon('./images/car.png'new BMap.Size(5226), { anchor: new BMap.Size(2713) }),
                        speed: 4500,
                        enableRotation: true,//是否设置marker随着道路的走向进行旋转
                        landmarkPois: [
                            { lng: 116.314782lat: 39.913508html: '加油站'pauseTime: 2 },
                            { lng: 116.315391lat: 39.964429html: '高速公路收费<div><img src="//map.baidu.com/img/logo-map.gif"/></div>'pauseTime: 3 },
                            { lng: 116.381476lat: 39.974073html: '肯德基早餐'pauseTime: 2 }
                        ]
                    });
                }
            }
        });
        var start = new BMap.Point(116.40484439.911836);
        var end = new BMap.Point(116.30810240.056057);
        drv.search(startend);
        //绑定事件
        $("run").onclick = function() {
            lushu.start();
        }
        $("stop").onclick = function() {
            lushu.stop();
        }
        $("pause").onclick = function() {
            lushu.pause();
        }
        $("hide").onclick = function() {
            lushu.hideInfoWindow();
        }
        $("show").onclick = function() {
            lushu.showInfoWindow();
        }

        function $(element) {
            return document.getElementById(element);
        }
    </script>
</body>

</html>

欢迎分享交流,转载请注明出处:WithCoder » 百度地图路书轨迹回放