欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

百度地图的轨迹回放和实时监控

程序员文章站 2022-07-05 13:07:59
...

最近写了两个页面,是跟百度地图有关的,本来以为是用的鹰眼的轨迹,才发现没那么麻烦,直接用的是百度地图自带的api。

1 轨迹回放

<template>
 <div class="map">
     <!--面包屑-->
    <span class="content_span">
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>后台管理</el-breadcrumb-item>
            <el-breadcrumb-item>人员管理</el-breadcrumb-item>
            <el-breadcrumb-item>{{this.$route.meta.title}}</el-breadcrumb-item>
        </el-breadcrumb>
    </span>

     <div class="left">
          <!-- 设备信息 -->
          <div class="she_bei">
              <h5>设备信息</h5>
              <el-form ref="form" :model="form1" label-width="80px">
                    <el-form-item label="所属班组:">
                        <el-select v-model="form2.class1" placeholder="请选择" @change="change1">
                            <el-option
                            v-for="item in class1"
                            :key="item.value"
                            :label="item.value"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备编号:">
                        <el-select v-model="form2.number" placeholder="请选择" @change="change2">
                            <el-option
                            v-for="item in number"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
              </el-form>
          </div>

          <!-- 时间 -->
          <div class="time">
             <h5>时间</h5>
             <el-form ref="form" :model="form2" label-width="80px">
                    <el-form-item label="开始时间:">
                         <el-date-picker
                            v-model="form2.value1"
                            type="datetime"
                            placeholder="开始时间">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="结束时间:">
                         <el-date-picker
                            v-model="form2.value2"
                            type="datetime"
                            placeholder="结束时间">
                        </el-date-picker>
                    </el-form-item>
              </el-form>
              <el-button size="mini" style="float:right;margin-right:35px;" @click="inquiry">轨迹查询</el-button>
          </div>

          <!-- 回放控制 -->
          <div class="hui_fang">
             <h5>回放控制</h5>
             <el-button size="mini" @click="play">开始</el-button>
             <el-button size="mini" @click="pause">暂停</el-button>
             <el-button size="mini" @click="reset">重放</el-button>
             <el-button size="mini" @click="clear">清除轨迹</el-button>
             <strong style="font-size:12px;margin-top:8px;display:block;">播放速率:</strong>
             <el-slider
                v-model="value3"
                :marks="marks"
                style="width:90%;margin-left:5%;"
                :step="1">
            </el-slider>
          </div>

          <!-- 状态 -->
          <div class="status">
              <h5>状态</h5>
              <div><span>总里程数:</span>约{{totalMi}}公里</div>
              <!-- <div><span>终端名称:</span>{{form2.number}}</div> -->
              <div><span>定位类型:</span>GPS+北斗</div>
              <div><span>当前速度:</span>{{speed}}km/h</div>
              <div><span>当前时间:</span>{{date}}</div>
              <div><span>轨迹时间:</span>约{{hour}}时{{minute}}分{{second}}秒</div>
              <!-- <div><span>现里程数:</span>约{{nowMi}}公里</div>
              <div><span>运动时间:</span></div>
              <div><span>停留时间:</span></div> -->
          </div>
     </div>
     <!-- 地图 -->
    <div id="map">
      
    </div>
    
 </div>
 
    
</template>

<script>
var _this;
import axios from '../../apiconfig/index.js';
import loadMap from '../../../static/js/loadBMap.js';
import GeoUtils from '../../../static/js/util.js';
const moment=require('moment');
export default {
    data(){
        return {
            // 设备信息
            equipment:[],
            form1:{
                class1:'',
                number:''
            },
            //所属班组
            class1:[],
            //设备编号
            number:[],
            // 时间
            form2:{
                value1:'',
                value2:''
            },
            // 可以调整播放速度
            value3:'',
            //当前速度
            speed:0,
            marks: {
                0: '0',
                25: '25',
                50: '50',
                75:'75',
                100:'100'
            },
            // 当前时间
            date:moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
            // 总里程数
            totalMi:0,
            // 现里程数
            nowMi:0,
            
            //轨迹的参数
            map:'',
            car:'',
            label:'',
            centerPoint:'',
            driving:'',
            timer:null,
            index:0,

            //轨迹时间
            hour:0,
            minute:0,
            second:0

        }
    },
    mounted(){
       _this=this;
       _this.baidu();
       _this.getEquipment();
       _this.form2.value1=moment(new Date()).format('YYYY-MM-DD 00:00:00');
       _this.form2.value2=moment(new Date()).format('YYYY-MM-DD 23:59:59');
    },
    methods:{
        //班组改变时
        change1(val){
           _this.form1.class1=val;
        },
        //设备列表改变时
        change2(val){
           _this.form1.number=val;
        },
        //获取设备列表
        getEquipment(){
           axios
           .get('/api/SafetyHat/GetEquipment')
           .then(res=>{
               console.log(res)
               if(res.ResultType==0){
                    _this.equipment=res.Data.pu;
                    _this.class1=_this.equipment.map((item)=>{
                        return {
                            value:item.LineID
                        }
                    })
                    _this.number=_this.equipment.map((item)=>{
                        return {
                            value:item.PuID,
                            label:item.PuName
                        }
                    })
                  console.log(_this.class1)
               }
           })
           .catch(error=>{
               console.log(error)
           })
        },
        baidu(){
            // panTo()方法将让地图平滑移动至新中心点,如果移动距离超过了当前地图区域大小,则地图会直跳到该点
            // new BMap.DrivingRoute(map);创建驾车实例
            loadMap('lGct54QCT9vLZ2b4miQlr5KirsBXI1Du').then(()=>{
                    var map = new BMap.Map("map");    // 创建Map实例
                    var point=new BMap.Point(114.471938,38.071433);

                    map.centerAndZoom(point, 11);  // 初始化地图,设置中心点坐标和地图级别
                    //添加地图类型控件
                    map.addControl(new BMap.MapTypeControl({
                        mapTypes:[
                            BMAP_NORMAL_MAP,
                            BMAP_HYBRID_MAP
                        ]}));	  
                    map.setCurrentCity("石家庄");          // 设置地图显示的城市 此项是必须设置的
                    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

                    var marker=new BMap.Marker(point);  //创建点
                    map.addOverlay(marker);//向地图添加覆盖物 
            })
        },
        // 开始
        play(){
            loadMap('lGct54QCT9vLZ2b4miQlr5KirsBXI1Du').then(()=>{
                var points = [];
                axios
                .get('/api/SafetyHat/GetTrajectory',{
                    params:{
                        LineID:_this.form1.class1,
                        PuID:_this.form1.number,
                        startTime:Date.parse(_this.form2.value1).toString().substr(0,10),
                        endTime:Date.parse(_this.form2.value2).toString().substr(0,10)
                    }
                })
                .then(res=>{
                    if(res.ResultType ==0){
                        for(var i=0;i<res.Data.length;i++){
                            points.push(new BMap.Point(res.Data[i].Longitude,res.Data[i].Latidude))
                        }
                        if(_this.index < points.length) {
                            _this.timer = window.setInterval(function(){
                                //位置的移动
                                _this.index++;
                                var point = points[_this.index];
                                _this.car.setPosition(point);
                                _this.map.addOverlay(_this.car);

                                //当前时间移动
                                var arr1=[];
                                for(var i=0;i<res.Data.length;i++){
                                    arr1.push(res.Data[i].GpsTime)
                                    arr1[i]=moment(arr1[i]*1000).format('YYYY-MM-DD HH:mm:ss')
                                }
                                _this.date=arr1[_this.index];

                                // 速度移动
                                var arr2=[];
                                for(var i=0;i<res.Data.length;i++){
                                    arr2.push(res.Data[i].Speed)
                                }
                                _this.speed=arr2[_this.index];

                                //清除定时器
                                if(_this.index == points.length){
                                    window.clearInterval(_this.timer)
                                    _this.date=arr1[arr1.length-1];
                                    _this.speed=0;
                                }
                            }, 500);
                        }
                    }
                })
                .catch(error=>{
                    console.log(error)
                })
            })
        },
        // 暂停
        pause(){
            if(_this.timer) {  
                window.clearInterval(_this.timer);  
            }
        },
        // 重放
        reset(){
            loadMap('lGct54QCT9vLZ2b4miQlr5KirsBXI1Du').then(()=>{
                var points = [];
                axios
                .get('/api/SafetyHat/GetTrajectory',{
                    params:{
                        LineID:_this.form1.class1,
                        PuID:_this.form1.number,
                        startTime:Date.parse(_this.form2.value1).toString().substr(0,10),
                        endTime:Date.parse(_this.form2.value2).toString().substr(0,10)
                    }
                })
                .then(res=>{
                    if(res.ResultType ==0){
                        for(var i=0;i<res.Data.length;i++){
                            points.push(new BMap.Point(res.Data[i].Longitude,res.Data[i].Latidude))
                        }
                        
                        points = _this.driving.getResults().getPlan(0).getRoute(0).getPath();
                        if(_this.timer) {  
                            window.clearInterval(_this.timer);  
                        }  
                        _this.index = 0;  
                        _this.car.setPosition(points[0]);
                        _this.play();
                        _this.centerPoint = new BMap.Point((points[0].lng + points[points.length - 1].lng) / 2, (points[0].lat + points[points.length - 1].lat) / 2);
                        _this.map.panTo(_this.centerPoint);
                    }
                })
                .catch(error=>{
                    console.log(error)
                })
            })
        },
        // 清除轨迹
        clear(){
           _this.map.clearOverlays();
           window.clearInterval(_this.timer);
        },
        // 查询
        inquiry(){
             loadMap('lGct54QCT9vLZ2b4miQlr5KirsBXI1Du').then(()=>{
                    var points = [];
                    axios
                    .get('/api/SafetyHat/GetTrajectory',{
                        params:{
                            LineID:_this.form1.class1,
                            PuID:_this.form1.number,
                            startTime:Date.parse(_this.form2.value1).toString().substr(0,10),
                            endTime:Date.parse(_this.form2.value2).toString().substr(0,10)
                        }
                    })
                    .then(res=>{
                        console.log(res)
                        if(res.ResultType ==0){
                            for(var i=0;i<res.Data.length;i++){
                                points.push(new BMap.Point(res.Data[i].Longitude,res.Data[i].Latidude))
                            }

                            //初始化地图,选取第一个点为起始点  
                            _this.map = new BMap.Map("map");  
                            _this.map.centerAndZoom(points[0],11);  
                            _this.map.enableScrollWheelZoom();  
                            _this.map.addControl(new BMap.NavigationControl());  
                            _this.map.addControl(new BMap.ScaleControl());  
                            _this.map.addControl(new BMap.OverviewMapControl({isOpen: true}));  


                            //通过DrivingRoute获取一条路线的point  
                            _this.driving = new BMap.DrivingRoute(_this.map);  
                            _this.driving.search(new BMap.Point(points[0].lng,points[0].lat), new BMap.Point(points[points.length-1].lng,points[points.length-1].lat));
                            _this.driving.setSearchCompleteCallback(function() { 
                                //画面移动到起点和终点的中间  
                                _this.centerPoint = new BMap.Point(points[0].lng,points[0].lat);  
                                _this.map.panTo(_this.centerPoint);  
                                //连接所有点  
                                _this.map.addOverlay(new BMap.Polyline(points, {strokeColor: "blue", strokeWeight:4, strokeOpacity: 1}));  
                                
                                //显示安全帽
                                _this.label = new BMap.Label("安全帽", {offset: new BMap.Size(-10, -20)}); 
            
                                var icon = new BMap.Icon('../../../static/imgs/cap.png', new BMap.Size(25, 20), {
                                    anchor: new BMap.Size(10, 20)
                                });
                                _this.car = new BMap.Marker(points[0],{icon:icon});
                                _this.car.setLabel(_this.label);  
                                _this.map.addOverlay(_this.car);
                            });
                            
                            //计算总里程数
                            var point1=new BMap.Polyline(points);//BMapLib.GeoUtils
                            _this.totalMi=(BMapLib.GeoUtils.getPolylineDistance(points).toFixed(0)/1000).toFixed(1);
                            console.log(points)

                            var end=res.Data[0].GpsTime-res.Data[res.Data.length-1].GpsTime;
                            _this.hour= parseInt((end % (60 * 60 * 24)) / ( 60 * 60));
                            _this.minute= parseInt((end % ( 60 * 60)) / ( 60));
                            _this.second= (end % (60));

                        }else{
                            _this.$message.error('获取轨迹失败!您所选时间暂时没有轨迹或者未选择班组和设备编号!');
                        }
                    })
                    .catch(error=>{
                        console.log(error)
                    })
             })
        }
    }
}
</script>

<style scoped>
/* .map{
  width:89%;
  height:900px;
  float:right;
} */
#map{
    width:81%;
    height:980px;
    float:right;
}
.left{
    width:19%;
    height:980px;
    float:left;
    background: #e0eeee;
    padding:10px 5px;
}
h5{
    position: relative;
}
h5:after{
    position: absolute;
    bottom:-6px;
    left:0;
    background: #ccc;
    width:100%;
    content:'';
    height:1px;
}
.she_bei,.time{
    font-size:13px;
}
.status{
    margin-top: 15px;
}
.status div{
    margin-top: 10px;
    font-size:13px;
    color:#999;
    padding-left: 10px;
    box-sizing: border-box;
}
.status div span{
    color:black;
    margin-right: 10px;
}
.hui_fang{
    margin-top: 15px;
}
</style>

 

2 实时监控

<template>
    <div class="monitor">
        <!--面包屑-->
        <span class="content_span">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>后台管理</el-breadcrumb-item>
                <el-breadcrumb-item>人员管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{this.$route.meta.title}}</el-breadcrumb-item>
            </el-breadcrumb>
        </span>
        <!-- 左侧信息 -->
        <div class="left">
            <el-tree 
              :data="data" 
              :props="defaultProps"
              show-checkbox
              @check-change="handleCheckChange">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>
                    <i :class="node.icon"></i>{{ node.label }}
                </span>              
            </span>
            </el-tree>
        </div>

        <!-- 地图 -->
        <div id="map">
        
        </div>

        <!-- 下面的展示区域 -->
        <div class="bottom">
              <el-table
                :data="tableData"
                style="width: 100%">
                <el-table-column
                    prop="Name"
                    label="设备名称"
                    width="200">
                </el-table-column>
                <el-table-column
                    prop="Address"
                    label="地理位置">
                </el-table-column>
                <el-table-column
                    prop="Speed"
                    label="速度"
                    width="200">
                </el-table-column>
                <el-table-column
                    prop="Time"
                    label="上报时间"
                    width="300">
                </el-table-column>
                <el-table-column
                    prop="IsStatus"
                    label="是否在线"
                    width="200">
                </el-table-column>
             </el-table>
        </div>
    </div>
</template>

<script>
var _this;
import axios from '../../apiconfig/index.js';
import loadMap from '../../../static/js/loadBMap';
const moment=require('moment');
export default {
    data(){
        return {
           data:[{
                label: '设备列表',
                children: [{
                    label: 'HBWS',
                        children: [{
                            label:"1095001"
                        }]
                }]
           }],
           defaultProps: {
              children: 'children',
              label: 'label'
           },

           map:'',
           point:'',
           marker:'',
           label:'',
           icon:'',
           timer:null,

           description:{
                type:String,
                default:'*'
           },
           pu:[],
           
           tableData:[]
           
        }
    },
    mounted(){
       _this=this;
       _this.getPuName();
       window.localStorage.removeItem('PuID');
       _this.baidu();
    },
    beforeDestroy(){
      clearInterval(_this.timer);
    },
    methods:{
       //获取getPuName
       getPuName(){
            axios
            .get('/api/SafetyHat/GetEquipment')
            .then(res=>{
                console.log(res)
                if(res.ResultType==0){
                    _this.pu=res.Data.pu;
                    _this.data[0].children[0].children=res.Data.pu.map((item)=>{
                        return {
                            label:item.PuName
                        }
                    })
                }
            })
            .catch(error=>{
                console.log(error)
            })
       },
       //设置定时器
       setDing(){
            if(localStorage.getItem('PuID') != undefined && localStorage.getItem('PuID') != null){
                //封装函数
                function move(){
                    console.log('666')                    
                        _this.map.removeOverlay(_this.marker);
                        axios
                        .get('/api/SafetyHat/Monitor',{
                            params:{
                                PuID:localStorage.getItem('PuID') || ''
                            }
                        })
                        .then(res=>{
                            console.log(res)
                            var PuName=_this.pu.find(itm=>{return itm.PuID==localStorage.getItem('PuID')}).PuName
                            if(res.ResultType==0){
                                _this.point=new BMap.Point(res.Data[0].Longitude,res.Data[0].Latidude);
                                if(res.Data[0].State == 1){
                                    _this.icon=new BMap.Icon('../../../static/imgs/map1.png', new BMap.Size(25, 20), {
                                            anchor: new BMap.Size(10, 20)
                                    });
                                }else{
                                    _this.icon=new BMap.Icon('../../../static/imgs/cap.png', new BMap.Size(25, 20), {
                                            anchor: new BMap.Size(10, 20)
                                    });
                                }
                                _this.map.centerAndZoom(_this.point, 17);
                                _this.label = new BMap.Label(PuName, {offset: new BMap.Size(-10, 25)});
                                _this.marker=new BMap.Marker(_this.point,{icon:_this.icon});
                                _this.marker.setLabel(_this.label)
                                _this.map.addOverlay(_this.marker);
                                
                                //点击出现框框
                                var opts ={
                                        width :250,
                                        height:200,
                                        title :"地址:",
                                }
                                var infoWindow =new BMap.InfoWindow('aaaaa',opts);// 创建信息窗口对象
                                _this.marker.addEventListener("click",function(){
                                    _this.map.openInfoWindow(infoWindow,_this.point);
                                });
                                //根据经纬度获取地址
                                var geolocation = new BMap.Geolocation();
                                var gc = new BMap.Geocoder();
                                var pointAdd = new BMap.Point(res.Data[0].Longitude, res.Data[0].Latidude);
                                gc.getLocation(pointAdd, function(rs){
                                    //console.log(rs.address)
                                    //点击给底部赋值
                                    _this.tableData=res.Data.map((item)=>{
                                        return {
                                            Name:PuName,
                                            Address:rs.address,
                                            Speed:item.Speed+'km/h',
                                            Time:moment(item.GpsTime*1000).format('YYYY-MM-DD HH:mm:ss'),
                                            IsStatus:item.State == 0 ? '在线':'不在线'
                                        }
                                    })
                                })

                            }
                        })
                        .catch(error=>{
                            console.log(error)
                        })                    
                }
                move();
                //调用定时器
                _this.timer=setInterval(move,20000);
            }
       },
       baidu(){
            // panTo()方法将让地图平滑移动至新中心点,如果移动距离超过了当前地图区域大小,则地图会直跳到该点
            // new BMap.DrivingRoute(map);创建驾车实例
            loadMap('lGct54QCT9vLZ2b4miQlr5KirsBXI1Du').then(()=>{
                    _this.map = new BMap.Map("map");    // 创建Map实例
                    _this.point=new BMap.Point(114.471938,38.071433);

                    _this.map.centerAndZoom(_this.point, 15);  // 初始化地图,设置中心点坐标和地图级别
                    //添加地图类型控件
                    _this.map.addControl(new BMap.MapTypeControl({
                        mapTypes:[
                            BMAP_NORMAL_MAP,
                            BMAP_HYBRID_MAP
                        ]}));	  
                    _this.map.setCurrentCity("石家庄");          // 设置地图显示的城市 此项是必须设置的
                    _this.map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
                    
                    //调用定时器
                    _this.setDing();
                    
            })
        },
        //多选框点击时
        handleCheckChange(data, checked, indeterminate) {
                if(checked==true){
                        var PuID=_this.pu.find(itm=>{return itm.PuName==data.label}).PuID;
                        window.localStorage.setItem('PuID',PuID);
                        axios
                        .get('/api/SafetyHat/Monitor',{
                            params:{
                                PuID:localStorage.getItem('PuID') || ''
                            }
                        })
                        .then(res=>{
                            console.log(res)
                            if(res.ResultType==0){
                                    _this.setDing();
                                } 
                        })
                        .catch(error=>{
                            console.log(error)
                        })
                }else{
                    window.localStorage.removeItem('PuID')
                    clearInterval(_this.timer);
                    _this.map.removeOverlay(_this.marker);
                }
        },
    }
}
</script>

<style scoped>
 /* .monitor{
    width:89%;
    height:900px;
    float:right;
 } */
 .left{
    width:15%;
    height:980px;
    float:left;
    background: #e0eeee;
    padding:10px 5px;
}
#map{
    width:85%;
    height:980px;
    float:right;
 }
.el-tree{
    background: #e0eeee;
    font-size:13px;
}
.bottom{
    width:89%;
    height:100px;
    position: absolute;
    left:11%;
    bottom:0;
}
.bottom .el-table{
    background: #eee;
}
</style>

这里边包含了轨迹回放和实时监控。轨迹回访里包括查询轨迹,开始,暂停,重放和清除轨迹;实时监控里包括了设备的实时查看监控。

写的备注有点不是很多,但是都是百度地图的api,还有一些js逻辑,没有别的东西。