Newer
Older
shipFront / src / views / overview / leafletMap - 副本.vue
[wangxitong] on 30 May 2022 25 KB v1.1.2
<template>
  <div class="panel-container">
    <div class="mapBox" id="leaflet-map"></div>
    <div class="select-content">
      <el-checkbox-group v-model="checked" @change="handleChecked" style="width:500px;padding-top: 5px;background-color: #ffffffee;padding-left: 20px;margin-right: 10px">
        <el-checkbox :disabled="!shipClickable" label="AIS船只">AIS船只</el-checkbox>
        <el-checkbox v-for="option in options" :label="option" :key="option">{{option}}</el-checkbox>
      </el-checkbox-group>
      <el-select v-model="planTime" placeholder="算法结果:时间选择" size="small" style="margin-right: 10px" v-show="checked.indexOf('算法结果')!==-1"  @change="initresult(true)">
        <el-option
          v-for="item in resultList"
          :key="item.time"
          :label="item.time"
          :value="item.time">
        </el-option>
      </el-select>
      <el-select v-model="taskId" placeholder="历史轨迹:任务选择" size="small"  v-show="checked.indexOf('历史轨迹')!==-1"  @change="initroute(true)">
        <el-option
          v-for="item in taskList"
          :key="item.id"
          :label="item.showLabel"
          :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="taskRobot" placeholder="展示机器人选择" size="small"  v-show="checked.indexOf('历史轨迹')!==-1" @change="selectRobot()" multiple>
        <el-option
          v-for="item in taskRobotList"
          :key="item.robotId"
          :label="item.robotId"
          :value="item.robotId">
        </el-option>
      </el-select>
      <el-date-picker
        v-show="checked.indexOf('历史轨迹')!==-1"
        v-model="timeRange"
        @change="initroute(true)"
        type="daterange"
        value-format="yyyy-MM-dd"
        range-separator="至"
        start-placeholder="轨迹开始日期"
        end-placeholder="轨迹结束日期"
        size="small"
        :picker-options="pickerOptions">
      </el-date-picker>
    </div>
  </div>
</template>
<script>
  import { getRobotList } from '@/api/robot'
  import { getTyphoonList } from '@/api/typhoon'
  import { getShipShipsInCircle } from '@/api/ship'
  import { getCurrentPlan,getTaskTimeList,getTaskList } from '@/api/task'
  import { getRobotHistory } from '@/api/robot'
  import { getDaysTime } from '@/utils/dateutils'

  import Leaflet from "leaflet";
  import 'leaflet/dist/leaflet.css'
  import 'leaflet-canvas-marker'
  var colors = ['#ff0000','#ff7e00', '#ffcc00', '#00a642', '#00bae2', '#0054ff','#b000aa','#ff2dcb', '#13c2c2','#56ca95' ]
  var _minTime = null
  var _maxTime = null
  var route = null
  var routeline = null
  var map = null
  export default {
    name: 'LeafletMap',
    components: {
      Leaflet
    },
    data() {
      return {
        //定义pickerOptions对象,这个对象中可以设置  onPick  disabledDate
        pickerOptions: {
          onPick(time) {
            //此处的time为选择日期时的结果,time为一个对象,有两个值,一个是maxDate,一个是minDate,详细见下图,
            //以下判断是只选择了一个值的时候,也就是默认的开始值。
            if (!time.maxDate&&time.minDate) {
              //时间跨度为1天,1天转化成毫秒就是   24 * 3600 * 1000
              let timeRange = 1 * 24 * 60 * 60 * 1000
              //最小值为选择的日期-跨度值
              _minTime = time.minDate.getTime() - timeRange
              //最大值为选择的日期+跨度值
              _maxTime = time.minDate.getTime() + timeRange
            } else if(!time.maxDate&&!time.minDate){
              //如果两个值都已经选择了,也就是已经选择完成,则将最大值和最小值设置为null
              _minTime = _maxTime = null
            }
          },
          disabledDate(time) {
            //当已经选择了两个日期时
            if (_minTime && _maxTime) {
              //如果已经选择了两个日期,则小于最小值和大于最大值的都要禁用
              return time.getTime() < _minTime || time.getTime() > _maxTime || time.getTime() > (Date.now())
            } else {
              //如果没有选择两个值,即选择了一个或者什么都没有选择的初始状态,禁用的日期是当前日期之前的日期
              return time.getTime() > (Date.now())
            }
          }
        },
        center: [30, 125],
        checked: ['台风数据'],
        options: [ '台风数据', '算法结果', '历史轨迹'],
        result:null,
        wind:null,
        ship:null,
        robot:null,
        shipClickable: true,
        routeClickable: true,
        reset_btn: null,
        taskRobot:[],
        taskRobotList:[],
        robotList:[],
        taskList:[],
        resultList:[],
        timeRange:[],
        planTime:'',
        taskId:'',
        timer: null, // 定时器
        timer1: null, // 定时器
        clock: 5, // 定时时间
        taskTypeList:[
          '','定向','航路点','定深直航','驻留','投放','任务终止'
        ]
      };
    },
    watch: {
      timeRange(val) {
        if (val && val.length > 0) {

        } else {
           _minTime = null
           _maxTime = null
        }
      }
    },
    beforeDestroy(){
      this.stopTimer()
    },
    mounted() {
      const { startTime, endTime } = getDaysTime()
      this.timeRange = [startTime, endTime]
      _minTime = new Date(startTime)
      _maxTime = new Date(endTime)
      this.initMap();
      this.initOption()
    },
    methods: {
      handleChecked(val){
        this.taskId = ''
        this.planTime = ''
        const { startTime, endTime } = getDaysTime()
        this.timeRange = [startTime, endTime]
        // this.initOption()
        this.initwind(val.indexOf('台风数据')!==-1)
        if(val.indexOf('AIS船只')!==-1){
          this.initais(true)
        }else{
          if(this.ship!==null && this.shipClickable){
            map.removeLayer(this.ship)
            this.ship.clearLayers()
          }
        }

        if(val.indexOf('历史轨迹')!==-1){
          getTaskList().then(res => {
            if (res.code === 200) {
              this.taskList = res.data.map(item => {
                if(item.taskType !== '')
                  item.showLabel = item.createTime + ' '+ this.taskTypeList[Number(item.taskType)]
                else item.showLabel = item.createTime
                return item
              })
              if(this.taskList.length!==0){
                this.taskId = this.taskList[0].id
                this.initroute(true)
              }
            }
          })
        }
        else{
          this.initroute(false)
        }
        if(val.indexOf('算法结果')!==-1){
          getTaskTimeList().then(res => {
            if (res.code === 200) {
              this.resultList = res.data
              if(this.resultList.length!==0){
                this.planTime = this.resultList[0].time
                this.initresult(true)
              }
            }
          })
        }
        else{
          this.initresult(false)
        }
      },
      async initrobot(){
        let icon = L.icon({
          iconUrl: require('@/assets/images/robot.png'),
          iconSize: [20, 20]
        })
        getRobotList().then(res => {
          if (res.code === 200) {
            let layers=[]
            this.robotList = res.data
            for (let i = 0; i < res.data.length; i++) {
              const { robotId,lat,lng,instrumentE,navigateState,powerE,targetDistance} = res.data[i]
              let str =  `
                      <div style="font-size: 15px;width:300px;">
                        <div style="font-weight: bold;padding-bottom: 10px;font-size: 16px; ">${robotId}号机器人</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">	航行状态:</label>${navigateState}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">经纬度:</label>${lng},${lat}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">仪表电余量:</label>${instrumentE}%</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">动力电余量:</label>${powerE}%</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">目标距离:</label>${targetDistance}</div>
                     </div>`
              let popup = L.popup().setContent(str)
              let marker = L.marker([lat, lng], { icon: icon }).bindPopup(popup)
              layers.push(marker)
            }
            // 加上新的
            let layerGroup = L.layerGroup(layers)
            map.addLayer(layerGroup)

            //删去旧的
            if(this.robot!==null){
              map.removeLayer(this.robot)
              this.robot.clearLayers()
            }

            // 赋值
            this.robot = layerGroup
            this.openTimer()
          }
        })

      },
      initOption(){
        getTaskList().then(res => {
          if (res.code === 200) {
            this.taskList = res.data.map(item => {
              if(item.taskType !== '')
                item.showLabel = item.createTime + ' '+ this.taskTypeList[Number(item.taskType)]
              else item.showLabel = item.createTime
              return item
            })
            if(this.taskList.length!==0)
              this.taskId = this.taskList[0].id
          }
        })
        getTaskTimeList().then(res => {
          if (res.code === 200) {
            this.resultList = res.data
          }
        })
    },
      selectRobot(){
        let that = this
        route.eachLayer(item =>{
          map.removeLayer(item)
          if(that.taskRobot.indexOf(item.options.name)!==-1){
            map.addLayer(item)
          }
        })
      },
      routeTimer(){
        if(!this.routeClickable){
          return
        }
        this.routeClickable = false
        if(route!==null){
          map.removeLayer(route)
          //route.clearLayers()
        }
        let params ={
          taskId:this.taskId,
          startDate:'',
          endDate:''
        }
        if (this.timeRange && this.timeRange.length > 0) {
          params.startDate = this.timeRange[0]
          params.endDate = this.timeRange[1]
        }

        getRobotHistory(params).then(res => {
          if (res.code === 200) {
            let layers=[]
            for (let i=0; i<res.data.length;i++) {
              let robot = res.data[i]
              let myStyle = {
                'color': colors[i],
                'weight': 3,
                'opacity': 0.7,
                'name': robot[0].robotId
              }
              let pathlist=[]
              for(const point of robot){
                pathlist.push( [point.lat, point.lng])
                var myIcon = L.divIcon({
                  html: '<div style="font-size: 15px;font-weight: bold;padding-top: 2px;border-radius: 50%;text-align:center;background-color: '+colors[i]+ '99;color: white"> ' +  point.robotId + '</div>',
                  className: '',
                  iconSize:[25,25]
                });
                let marker=L.marker([point.lat,point.lng], { icon: myIcon, name: point.robotId })
                layers.push(marker)
              }
              let line = L.polyline(pathlist, myStyle)
              layers.push(line)
            }
            route = L.layerGroup(layers)
            map.addLayer(route)
            this.selectRobot()
            this.routeClickable = true
          }
        })
      },
      async initroute(isShow){
        if(this.timeRange.length === 0){return}
        if(new Date(this.timeRange[1]).getTime() - new Date(this.timeRange[0]).getTime()> 1*24*60*60*1000){
          this.$message.warning('时间范围超过一天')
          return
        }
        this.taskRobotList = []
        this.taskRobot = []
        if(route!==null){
          map.removeLayer(route)
          //route.clearLayers()
        }
        if(!isShow) {
          this.stopTimer1()
          map.removeLayer(route)
          // route.clearLayers()
          return
        }
        this.routeClickable = false
        let params ={
          taskId:this.taskId,
          startDate:'',
          endDate:''
        }
        if (this.timeRange && this.timeRange.length > 0) {
          params.startDate = this.timeRange[0]
          params.endDate = this.timeRange[1]
        }
        getRobotHistory(params).then(res => {
          if (res.code === 200) {
            let layers=[]
            this.taskRobotList = res.data.map(item => item[0])
            this.taskRobot =this.taskRobotList.map(item =>item.robotId)

            route = L.canvasIconLayer({}).addTo(map)

            for (let i=0; i<res.data.length;i++) {
              let robot = res.data[i]
              let myStyle = {
                'color': colors[i],
                'weight': 3,
                'opacity': 0.7,
                'name': robot[0].robotId
              }
              let pathlist=[]
              for(const point of robot){
                pathlist.push( [point.lat, point.lng])
                let myIcon = L.divIcon({
                  html: '<div style="font-size: 15px;font-weight: bold;padding-top: 2px;border-radius: 50%;text-align:center;background-color: '+colors[i]+ '99;color: white"> ' +  point.robotId + '</div>',
                  iconSize:[25,25]
                });
                let iconUrl = require(`@/assets/images/${point.robotId}.png`)
                let icon = window.L.icon({
                  iconUrl: iconUrl,
                  iconSize: [20, 20],
                  iconAnchor: [10,10]
                })
                let marker=L.marker([point.lat,point.lng], { icon: icon, name: point.robotId })
                // layers.push(marker)
                route.addLayer(marker)
              }
              //let line = L.polyline(pathlist, myStyle)
              // layers.push(line)
            }
            // route = L.layerGroup(layers)
            // map.addLayer(route)
            let center = map.getCenter()
            map.panTo([center.lat, center.lng], {
              animate: true
            })

            this.routeClickable = true
            // this.openTimer1()
          }
        })
      },
      async initresult(isShow){
        if(this.result!==null){
          map.removeLayer(this.result)
          this.result.clearLayers()
        }
        if(!isShow) return
        let params ={
          planTime:this.planTime
        }
        let myStyle = {
          'color': '#56ca95',
          'weight': 3,
          'opacity': 0.7
        }
        let myStyle1 = {
          'color': '#7ba6e9',
          'weight': 2,
          'opacity': 0.9
        }
        getCurrentPlan(params).then(res => {
          if (res.code === 200) {
            let layers=[]
            let pathlist=[]
            // 规划区域 0:多边形  1:圆形
            if(res.data.regionResult.contour==='0'){
              for(const point of res.data.regionResult.regionPoints){
                pathlist.push( [point.lat, point.lng])
              }
              layers.push( L.polygon(pathlist, myStyle1))
              for(const point of pathlist){
                layers.push( L.circle(point, {
                  color: '#f98e11',
                  fillColor: '#f98e11',
                  fillOpacity: 1,
                  radius: 10
                }))
              }
            } else if(res.data.regionResult.contour==='1'){
              layers.push(L.circle([res.data.regionResult.regionPoints[0].lat,res.data.regionResult.regionPoints[0].lng], {
                color: '#7ba6e9',
                fillColor: '#7ba6e9',
                fillOpacity: 0.7,
                radius: res.data.regionResult.regionRadius*1000
              })) // 区域
              layers.push( L.circle([res.data.regionResult.regionPoints[0].lat,res.data.regionResult.regionPoints[0].lng], {
                color: '#f98e11',
                fillColor: '#f98e11',
                fillOpacity: 1,
                radius: 10
              })) // 圆心
            }
            pathlist=[]
            //机器规划点
            if(res.data.regionResult!==''){
              let arr = res.data.regionResult.robotIds.split(',')
              for(let i=0;i< res.data.regionResult.robotTargets.length;i++){
                let point = res.data.regionResult.robotTargets[i]
                pathlist.push( [point.lat, point.lng])
                var myIcon = L.divIcon({
                  html: '<div style="font-size: 10px; width: 0;' +
                    'height: 0;' +
                    'border-left: 10px solid transparent;' +
                    'border-right: 10px solid transparent;' +
                    'border-bottom: 20px solid #50c55c;' +
                    'text-align:center;color: white"/> ', // +  arr[i] + '</div>',
                  className: '',
                  iconSize:[20,20]
                });
                let str =  `
                      <div style="font-size: 15px;width:300px;">
                        <div style="font-weight: bold;padding-bottom: 10px;font-size: 16px; ">区域规划${arr[i]}号机器人</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">经纬度:</label>${point.lng},${point.lat}</div>
                     </div>`
                let popup = L.popup().setContent(str)
                let marker=L.marker([point.lat,point.lng], { icon: myIcon }).bindPopup(popup)
                layers.push(marker)
              }
            }
            // 规划路线
            for (const robot of res.data.routeResult) {
              pathlist=[]
              if(robot.routeModel==='') continue
              for(const point of robot.routeModel.robotRoutes){
                pathlist.push( [point.lat, point.lng])
                var myIcon = L.divIcon({
                  html: '<div style="font-size: 15px;font-weight: bold;border-radius: 50%;text-align:center;background-color: #50c55c99;color: white"> ' +  robot.robotId + '</div>',
                  className: '',
                  iconSize:[25,25]
                });
                let str =  `
                      <div style="font-size: 15px;width:300px;">
                        <div style="font-weight: bold;padding-bottom: 10px;font-size: 16px; ">路线规划${ robot.robotId}号机器人</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">经纬度:</label>${point.lng},${point.lat}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">深度:</label>${point.depth}m</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">航向角:</label>${point.headingAngle}°</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">俯仰角:</label>${point.pitchAngle}°</div>
                     </div>`
                let popup = L.popup().setContent(str)
                let marker=L.marker([point.lat,point.lng], { icon: myIcon }).bindPopup(popup)
                layers.push(marker)
              }
              let line = L.polyline(pathlist, myStyle)
              layers.push(line)
            }
            this.result = L.layerGroup(layers)
            map.addLayer(this.result)
          }
        })
      },
      async initwind(isShow) {
        let icon = L.icon({
          iconUrl: require('@/assets/images/wind.png'),
          iconSize: [20, 20]
        })
        if(this.wind!==null){
          map.removeLayer(this.wind)
          this.wind.clearLayers()
        }
        if(isShow){
          getTyphoonList().then(res => {
            if (res.code === 200) {
              let layers=[]
              for (let i = 0; i < res.data.length; i++) {
                const { centerPressure, engName, moveDirection, moveSpeed, power,lat,lng, speed, radius10, radius7, time, typhoonType, name} = res.data[i]
                let str =  `
                      <div style="font-size: 15px;width:300px;">
                        <div style="font-weight: bold;padding-bottom: 10px;font-size: 16px; ">${engName}(${name})</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">	台风中心气压:</label>${centerPressure}百帕</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">台风代号:</label>${engName}(${name})</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">经纬度:</label>${lng},${lat}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">台风移动:</label>${moveDirection}方向${moveSpeed}公里/小时</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">风力:</label>${power}级</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">风速:</label>m/s${speed}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">10级风力影响半径:</label>${radius10}公里</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">7级风力影响半径:</label>${radius7}公里</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">数据更新时间:</label>${time}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">台风描述:</label>${typhoonType}</div>
                     </div>`
                let popup = L.popup().setContent(str)
                let marker = L.marker([lat, lng], { icon: icon }).bindPopup(popup)
                layers.push(marker)
              }
              this.wind = L.layerGroup(layers)
              map.addLayer(this.wind)
            }
          })
        }
      },
      async initais(isShow) {
        let icon = L.icon({
          iconUrl: require('@/assets/images/ship.png'),
          iconSize: [30, 30]
        })

        if(isShow && this.shipClickable){
          if(this.ship!==null){
            map.removeLayer(this.ship)
            this.ship.clearLayers()
          }
          this.shipClickable = false
          let layers=[]
          for (let r = 0; r < this.robotList.length ;r++) {
            let rgn = Number(this.robotList[r].lat).toFixed(5)*600000+','+Number(this.robotList[r].lng).toFixed(5)*600000+',50'
            await getShipShipsInCircle(rgn).then(res => {
              if (res.code === 200) {
                for (let i = 0; i < res.data.length; i++) {
                  const { shipId,aisStatus,lng,lat,course,speed,heading,depth,imoNum,shipCallNum,shipType,shipLength,shipWidth,destination,expectTime,positionTime} = res.data[i]
                  let str =  `
                      <div style="font-size: 15px;width:300px;">
                        <div style="font-weight: bold;padding-bottom: 10px;font-size: 16px; ">${shipId}号船舶</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">	ais状态:</label>${aisStatus}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">经纬度:</label>${lng},${lat}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">航向:</label>${course}°</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">航速:</label>${speed}节</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">目的港:</label>${destination}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">预到时间:</label>${expectTime}</div>
                        <div style="padding-bottom: 3px"><label style="padding-right: 5px">定位时间:</label>${positionTime}</div>
                     </div>`
                  let popup = L.popup().setContent(str)
                  let marker = L.marker([lat, lng], { icon: icon }).bindPopup(popup)
                  layers.push(marker)
                }
                if(r===  this.robotList.length-1){
                  this.ship = L.layerGroup(layers)
                  map.addLayer(this.ship)
                  this.shipClickable = true
                }
              }
            })
          }
        }
      },
      openTimer(){
        this.timer = setTimeout(() => {
          this.initrobot()
        }, this.clock * 1000)
      }, // 停止定时器
      openTimer1(){
        this.timer1 = setInterval(() => {
          this.routeTimer()
        }, 2 * 1000)
      }, // 停止定时器
      stopTimer(){
        if (this.timer){
          clearTimeout(this.timer)
          this.timer = null
        }
        if (this.timer1){
          clearTimeout(this.timer1)
          this.timer1 = null
        }
      },
      stopTimer1(){
        if (this.timer1){
          clearTimeout(this.timer1)
          this.timer1 = null
        }
      },
      initMap() {
        map = L.map('leaflet-map', {
          crs: L.CRS.EPSG3857
        });
        map.setView(this.center, 2);
        var myDemo = L.tileLayer.wms(this.baseConfig.mapserverUrl + "cgi-bin/mapserv.exe?MAP=D:/ms4w/ms4w/apps/worldmap/world3857.map", {
          layers: 'DEPARE,LNDARE,SBDARE,RIVERS,WRECKS,OFSPLF,UWTROC,DEPARE1,LNDARE1,SBDARE1,RIVERS1,WRECKS1,OFSPLF1,UWTROC1',
          format: 'image/png',
          transparent: false,
          crs: L.CRS.EPSG3857,
          minZoom:4
        });
        myDemo.addTo(map);
        this.initrobot()
        this.initwind(true)
      },
    },
  };
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .panel-container {
    width: 100%;
    height: 100%;
    position:relative;
    overflow: auto;
    flex: 1;
  }
  .mapBox{
    width: 100%;
    position:absolute;
    top: 0;
    bottom:0;
    overflow: hidden;
    /*z-index: 9;*/
  }
  .select-content{
    position:absolute;
    left: 60px;
    top: 0px;
    height: 42px;
    width: 1400px;
    padding-top: 10px;
    z-index: 1000;
    display: flex;
  }
</style>