forked from drone/command-center-dashboard

罗广辉
2025-04-21 2800fa4f32f3900509cb4d6eefaf2bfaf54efdd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
<template>
    <div id="taskMap"></div>
</template>
<script setup>
import * as Cesium from 'cesium'
import { Cartesian3, Math as CesiumMath, Terrain, Viewer } from 'cesium'
import AmapMercatorTilingScheme from '@/utils/cesium/AmapMercatorTilingScheme'
import { analyzeKmzFile, removeTextKey, XMLToJSON } from '@/utils/cesium/kmz'
import ImageTrailMaterial from '@/utils/cesium/ImageTrailMaterial'
import lineImg from '@/assets/images/arrow-right-blue.png'
import Startingpointicon from '@/assets/images/Startingpointicon.png'
import EndPointicon from '@/assets/images/EndPointicon.png'
import uavImg from '@/assets/images/home/useUavHome/uavImg.png'
import { getCenterPoint } from '@/utils/cesium/mapUtil'
import { getWaylineByArea } from '@/api/home/task'
import { useStore } from 'vuex'
import { addBlueFilter } from '@/utils/cesium/common'
// 新图片
import newStartPoint from '@/assets/images/newStartPoint.png'
import newEndPointImg from '@/assets/images/newEndPointicon.png'
import newlineImg from '@/assets/images/newarrow-right.png'
const store = useStore()
const userAreaPosition = computed(() => store.state.home.userAreaPosition)
 
// 声明事件
const emit = defineEmits(['clickPosition', 'saveWayline'])
 
const props = defineProps({
    wayLineFile: {
        type: String,
        default: '',
    },
    checkedTableData: {
        type: Array,
        default: () => [],
    },
    waylineTypeTest: {
        type: Number,
        default: 3,
    },
})
 
const imageryProvider_ammapSL = new Cesium.UrlTemplateImageryProvider({
    url: 'https://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
    layer: 'tdtVecBasicLayer',
    style: 'default',
    format: 'image/png',
    tileMatrixSetID: 'GoogleMapsCompatible',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    maximumLevel: 18,
    tilingScheme: new AmapMercatorTilingScheme(),
    credit: 'amap_SL',
})
 
let viewer = null
let currentEntity = null
let connectLines = [] // 存储连接线实体
let polygonPoints = [] // 存储多边形的点
let polygonEntity = null // 存储多边形实体
let existingEntity = null // 后端返回数据生成得面状线
// 添加变量跟踪当前菜单
let currentMenu = null
 
const init = () => {
    viewer = new Viewer('taskMap', {
        terrain: Terrain.fromWorldTerrain(),
        infoBox: false, // 禁用沙箱,解决控制台报错
        animation: false, // 左下角的动画仪表盘
        baseLayerPicker: false, // 右上角的图层选择按钮
        geocoder: false, // 搜索框
        homeButton: false, // home按钮
        sceneModePicker: false, // 模式切换按钮
        timeline: false, // 底部的时间轴
        navigationHelpButton: false, // 右上角的帮助按钮,
        selectionIndicator: false, // 是否显示选择指示器
        baseLayer: false,
        fullscreenButton: false,
        // sceneMode: Cesium.SceneMode.COLUMBUS_VIEW,
    })
    const gdLayer = viewer.imageryLayers.addImageryProvider(imageryProvider_ammapSL)
    const options = {
        bInvertColor: true,
        bFilterColor: true,
        filterColor: '#4e70a6',
    }
    // 添加蓝色滤镜
    addBlueFilter(options, viewer, gdLayer)
    viewer.scene.morphTo2D(0)
    //设置默认点
    const { longitude = 115.763819, latitude = 28.787374, height = 10 } = userAreaPosition.value || {}
    viewer.camera.setView({
        destination: Cartesian3.fromDegrees(longitude, latitude, height),
    })
}
 
// 单点左键点击事件
const singlePointLeftClick = () => {
    viewer.screenSpaceEventHandler.setInputAction(click => {
        if (props.waylineTypeTest !== 1) return
        const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
        if (cartesian) {
            // 清除之前的实体
            viewer.entities.removeAll()
 
            // 添加新点
            const point = viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 10,
                    color: Cesium.Color.fromCssColorString('#1FFF69'),
                },
            })
 
            // 转换坐标
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
            const longitude = Cesium.Math.toDegrees(cartographic.longitude)
            const latitude = Cesium.Math.toDegrees(cartographic.latitude)
 
            // 更新当前实体引用
            currentEntity = point
 
            // 发送坐标
            emit('clickPosition', { longitude, latitude })
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
 
// 智能规划航线
const intelligentPlanning = () => {
    // 添加点击事件监听
    viewer.screenSpaceEventHandler.setInputAction(click => {
        if (props.waylineTypeTest !== 2) return
        const cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid)
 
        if (cartesian) {
            // 添加新点
            const point = viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 10,
                    color: Cesium.Color.fromCssColorString('#1FFF69'),
                },
            })
 
            // 存储点位
            polygonPoints.push(cartesian)
 
            // 当点击超过2个点时绘制多边形
            if (polygonPoints.length > 2) {
                // 移除旧的多边形
                if (polygonEntity) {
                    viewer.entities.remove(polygonEntity)
                }
 
                // 创建新的多边形
                polygonEntity = viewer.entities.add({
                    polygon: {
                        hierarchy: new Cesium.PolygonHierarchy(polygonPoints),
                        // material: new Cesium.Color.fromBytes(212, 46, 32, 100),
                        material: new Cesium.Color(0, 0.5, 1, 0.3), // 蓝色
                        outline: true,
                        // outlineColor: new Cesium.Color.fromBytes(212, 46, 32, 255),
                        outlineColor: new Cesium.Color(0, 0.5, 1, 1), // 蓝
                        outlineWidth: 2,
                        height: 0, // Set explicit height
                        heightReference: Cesium.HeightReference.NONE, // Disable terrain clamping
                    },
                })
            }
 
            // 转换坐标并发送
            const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
            const longitude = Cesium.Math.toDegrees(cartographic.longitude)
            const latitude = Cesium.Math.toDegrees(cartographic.latitude)
            // emit('clickPosition', cartographic);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    // 修改右键点击事件,添加菜单
    viewer.screenSpaceEventHandler.setInputAction(movement => {
        if (props.waylineTypeTest !== 2) return
        if (polygonPoints.length > 2) {
            // 清除之前的菜单
            if (currentMenu) {
                document.body.querySelectorAll('.context-menu').forEach(menu => menu.remove())
            }
 
            const menuContainer = document.createElement('div')
            menuContainer.className = 'context-menu'
 
            // 获取地图容器
            const mapContainer = document.getElementById('taskMap')
            // 使用鼠标右键点击的实际位置
            menuContainer.style.position = 'absolute'
            menuContainer.style.left = `${movement.position.x}px`
            menuContainer.style.top = `${movement.position.y}px`
            menuContainer.style.zIndex = '1000'
 
            menuContainer.innerHTML = `
                <div class="menu-item" id="saveWayline">保存航线</div>
                <div class="menu-item" id="cancelDraw">取消绘制</div>
            `
 
            mapContainer.appendChild(menuContainer)
            currentMenu = menuContainer
 
            // 添加全局点击事件监听
            const handleClickOutside = e => {
                if (!menuContainer) return
                const isClickInside = menuContainer.contains(e.target)
                if (!isClickInside) {
                    menuContainer.remove()
                    document.removeEventListener('mousedown', handleClickOutside)
                }
            }
 
            // 延迟添加事件监听,避免右键点击立即触发
            setTimeout(() => {
                document.addEventListener('mousedown', handleClickOutside)
            }, 100)
 
            // 菜单按钮点击事件
            document.getElementById('saveWayline').onclick = () => {
                const coordinates = polygonPoints.map(point => {
                    const cartographic = Cesium.Cartographic.fromCartesian(point)
                    return {
                        longitude: Cesium.Math.toDegrees(cartographic.longitude),
                        latitude: Cesium.Math.toDegrees(cartographic.latitude),
                    }
                })
                emit('saveWayline', coordinates)
                saveWaylineByArea(coordinates)
                mapContainer.removeChild(menuContainer)
            }
 
            document.getElementById('cancelDraw').onclick = () => {
                polygonPoints = []
                viewer.entities.removeAll()
                mapContainer.removeChild(menuContainer)
            }
        }
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}
 
// 保存航线并且获取线
const saveWaylineByArea = dataValue => {
    const polygonArray = dataValue.map(point => [point.longitude, point.latitude])
    getWaylineByArea({ type: 2, polygon: polygonArray }).then(res => {
        if (res.data.code !== 0) retrun
        drawResultWayline(res.data.data)
    })
}
 
// 绘制后端生成得面状线
const drawResultWayline = dataValue => {
    // 先检查并删除已存在的航线
    existingEntity = viewer.entities.getById('result_wayline')
    if (existingEntity) {
        viewer.entities.remove(existingEntity)
    }
    const cartesian3List = ref([])
    dataValue.forEach(lnglat => {
        const cartesian3 = Cesium.Cartesian3.fromDegrees(
            Number(lnglat.x),
            Number(lnglat.y),
            Number(100) // 默认100
        )
        cartesian3List.value.push(cartesian3)
    })
    const setting = {
        id: 'result_wayline',
        polyline: {
            width: 2,
            positions: cartesian3List.value,
            material: Cesium.Color.CHARTREUSE,
        },
    }
    existingEntity = viewer?.entities.add({
        polyline: setting.polyline,
        id: setting.id,
    })
}
 
// 选中航线时调用 渲染线和点 type = 0
const renderingLine = lineObj => {
    const positions = lineObj.Placemark.map(item => {
        const [lon, lat] = item.Point.coordinates.split(',')
        return Cartesian3.fromDegrees(Number(lon), Number(lat))
    })
 
    viewer.entities.add({
        polyline: {
            width: 5,
            positions: positions,
            // material: new ImageTrailMaterial({
            //     color: { alpha: 1, blue: 1, green: 1, red: 1 },
            //     speed: 20,
            //     image: newlineImg,
            //     repeat: { x: Math.floor(40), y: 1 },
            // }),
            material: new Cesium.PolylineGlowMaterialProperty({
                // color: Cesium.Color.GREEN,
                image: newlineImg,
            }),
            clampToGround: false,
        },
    })
 
    positions.forEach((point, index) => {
        let setting = {}
        // if (index === 0) {
        //   //TODO
        // }
        // else if (index === 1) {
        //   setting = {
        //     position: point,
        //     id: `point_${index}`,
        //     billboard: {
        //       image: Startingpointicon,
        //       outlineWidth: 0,
        //       width: 20,
        //       height: 20,
        //       scale: 1.0,
        //     },
        //   }
        // } else
        if (index === positions.length - 1) {
            setting = {
                position: point,
                id: `point_${index}`,
                billboard: {
                    image: newEndPointImg,
                    outlineWidth: 0,
                    width: 20,
                    height: 20,
                    scale: 1.0,
                },
            }
        } else {
            setting = {
                position: point,
                id: `point_${index}`,
                label: {
                    text: `${index + 1}`,
                    font: 'bold 14px serif',
                    fillColor: Cesium.Color.WHITE,
                    //     style: Cesium.LabelStyle.FILL,
                    //     verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直居中
                    //     horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 水平居中
                        pixelOffset: new Cesium.Cartesian2(2, 0), // 根据需要调整偏移量
                    eyeOffset: new Cesium.Cartesian3(0, 0, -10), // 使标签在点的上方
                },
                billboard: {
                    image: new Cesium.ConstantProperty(newStartPoint),
                    width: 70,
                    height: 70,
                },
                // point: {
                //     pixelSize: 24,
                //     color: new Cesium.Color.fromBytes(255, 186, 0, 255),
                // },
 
                offset: new Cesium.Cartesian2(10, 30),
            }
        }
        viewer.entities.add(setting)
    })
}
 
// 飞到中心点
function flyToPoints(lngLatArr) {
    if (!Array.isArray(lngLatArr) || lngLatArr.length === 0) return
    const positions = lngLatArr.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(Number(lon), Number(lat)))
    // 计算包围盒 BoundingSphere(所有点的外接球)
    const boundingSphere = Cesium.BoundingSphere.fromPoints(positions)
    viewer.camera.flyToBoundingSphere(boundingSphere, {
        duration: 0,
        offset: new Cesium.HeadingPitchRange(0, 0, boundingSphere.radius * 2),
    })
}
 
// 异步解析kmz文件
const analysis = async url => {
    return new Promise(async resolve => {
        const res = await analyzeKmzFile(`${url}?_t=${new Date().getTime()}`)
        const templateXML = await res.fileInfoObj['wpmz/template.kml']
        const templateXMLJSON = XMLToJSON(templateXML)?.['Document']
        const templateXMLObj = removeTextKey(templateXMLJSON.Folder)
        resolve(templateXMLObj)
    })
}
 
// 绘制线和飞行
const drawLine = async () => {
    let prexUrl = ref(import.meta.env.VITE_APP_AIRLINE_URL + props.wayLineFile)
    const res = await analysis(prexUrl.value)
    if (!res.Placemark.length) return
    renderingLine(res)
    const points = res.Placemark.map(item => item.Point.coordinates.split(','))
    flyToPoints(points)
}
 
// 选择航线时,根据选择机巢连线
const selectLineFile = newVal => {
    // 清除之前的实体
    // viewer.entities.removeAll();
    // 重新绘制航线
    // if (props.wayLineFile) {
    //   drawLine();
    // }
    // 添加选中点和连接线
    const positions = newVal.map(item => {
        const position = Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude))
        // 添加机巢点
        viewer.entities.add({
            position: position,
            billboard: {
                image: new Cesium.ConstantProperty(uavImg),
                width: 24,
                height: 24,
            },
        })
        return position
    })
 
    // 添加连接线
    if (positions.length > 1) {
        viewer.entities.add({
            polyline: {
                positions: positions,
                width: 2,
                material: new Cesium.PolylineDashMaterialProperty({
                    color: Cesium.Color.RED,
                    dashLength: 8.0,
                }),
            },
        })
    }
    // 飞到中心点
    const lngLatArr = newVal.map(item => [item.longitude, item.latitude])
    flyToPoints(lngLatArr)
}
 
// 单个点生成选择多个机巢生成航线
const singlePointLines = newVal => {
    // 清除之前的连接线
    connectLines.forEach(line => viewer.entities.remove(line))
    connectLines = []
 
    if (currentEntity) {
        // 获取当前点的位置
        const currentPosition = currentEntity.position.getValue()
 
        // 为每个选中的机巢创建点和连接线
        newVal.forEach(item => {
            // 创建机巢点
            const nestPosition = Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude))
            viewer.entities.add({
                position: nestPosition,
                billboard: {
                    image: new Cesium.ConstantProperty(uavImg),
                    width: 24,
                    height: 24,
                },
            })
 
            // 创建连接线
            const line = viewer.entities.add({
                polyline: {
                    positions: [currentPosition, nestPosition],
                    width: 2,
                    material: new Cesium.PolylineDashMaterialProperty({
                        color: Cesium.Color.RED,
                        dashLength: 8.0,
                    }),
                },
            })
            connectLines.push(line)
        })
 
        // 飞到所有点的中心位置
        const lngLatArr = newVal.map(item => [item.longitude, item.latitude])
        flyToPoints(lngLatArr)
    }
}
 
// 智慧规划航线-面状航线
const planarPointsLines = newVal => {
    // 如果存在面状航线
    if (existingEntity) {
        const waylinePositions = existingEntity.polyline.positions.getValue()
 
        newVal.forEach(item => {
            // 创建机巢点
            const nestPosition = Cartesian3.fromDegrees(Number(item.longitude), Number(item.latitude))
 
            // 添加机巢图标
            viewer.entities.add({
                position: nestPosition,
                billboard: {
                    image: new Cesium.ConstantProperty(uavImg),
                    width: 24,
                    height: 24,
                },
            })
 
            // 找到最近的航线点并连线
            let minDistance = Number.MAX_VALUE
            let closestPosition = null
 
            waylinePositions.forEach(waylinePos => {
                const distance = Cartesian3.distance(nestPosition, waylinePos)
                if (distance < minDistance) {
                    minDistance = distance
                    closestPosition = waylinePos
                }
            })
 
            // 创建连接线
            if (closestPosition) {
                const line = viewer.entities.add({
                    polyline: {
                        positions: [nestPosition, closestPosition],
                        width: 2,
                        material: new Cesium.PolylineDashMaterialProperty({
                            color: Cesium.Color.CHARTREUSE,
                            dashLength: 8.0,
                        }),
                    },
                })
                connectLines.push(line)
            }
        })
 
        // 飞到所有点的中心位置
        const lngLatArr = newVal.map(item => [item.longitude, item.latitude])
        flyToPoints(lngLatArr)
    }
}
 
// 监听选择航线文件事件
watch(
    () => props.wayLineFile,
    async (newVal, oldValue) => {
        await removeMap()
        if (newVal) {
            await drawLine()
        }
    },
    { deep: true }
)
 
// 监听表格选中数据变化
watch(
    () => props.checkedTableData,
    newVal => {
        if (newVal.length > 0 && props.waylineTypeTest === 0) {
            selectLineFile(newVal)
        } else if (newVal.length > 0 && props.waylineTypeTest === 1) {
            singlePointLines(newVal)
        } else if (newVal.length > 0 && props.waylineTypeTest === 2) {
            planarPointsLines(newVal)
        }
    },
    { deep: true }
)
 
// 监听航线类型
watch(
    () => props.waylineTypeTest,
    async newVal => {
        await removeMap()
        if (newVal === 1) {
            await singlePointLeftClick()
        } else if (newVal === 2) {
            await intelligentPlanning()
        }
    },
    { deep: true }
)
 
const removeEvent = () => {
    // 清除事件监听器
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}
 
const removeMap = () => {
    // 清除所有实体
    if (viewer) {
        // 清除连接线
        connectLines.forEach(line => viewer.entities.remove(line))
        connectLines = []
 
        // 清除多边形点和实体
        polygonPoints = []
        if (polygonEntity) {
            viewer.entities.remove(polygonEntity)
        }
 
        // 清除当前实体和面状航线
        if (currentEntity) {
            viewer.entities.remove(currentEntity)
        }
        if (existingEntity) {
            viewer.entities.remove(existingEntity)
        }
 
        viewer.entities.removeAll()
 
        // 重置所有变量
        currentEntity = null
        polygonEntity = null
        existingEntity = null
    }
}
 
onBeforeUnmount(() => {
    removeMap()
    removeEvent()
    // 移除所有实体并销毁viewer
    viewer.destroy()
    viewer = null
})
 
onMounted(() => {
    nextTick(() => {
        init()
    })
})
</script>
<style scoped lang="scss">
#taskMap {
    position: relative;
    height: 100%;
 
    :deep() {
        .cesium-viewer {
            height: 100%;
            overflow: hidden;
 
            .cesium-viewer-cesiumWidgetContainer {
                width: 100%;
                height: 100%;
 
                .cesium-widget {
                    width: 100%;
                    height: 100%;
 
                    canvas {
                        width: 100%;
                        height: 100%;
                    }
                }
            }
        }
 
        .cesium-viewer-bottom {
            display: none;
        }
    }
 
    :deep(.context-menu) {
        position: absolute;
        background: rgba(0, 21, 41, 0.9);
        border-radius: 4px;
        padding: 8px 0;
        min-width: 120px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
 
        .menu-item {
            padding: 8px 16px;
            color: #fff;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
 
            &:hover {
                background: rgba(255, 255, 255, 0.1);
            }
        }
    }
}
</style>