无人机管理后台前端(已迁走)
张含笑
2025-11-03 5dc1eb8074f52b2fdc03216b62ae4e2d82acbe0f
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
<template>
  <basic-container>
    <div class="layerContainer">
      <div>
        <el-tabs v-model="activeType" @tab-click="handleClick">
          <el-tab-pane v-for="tab in tabData" :key="tab.type" :label="tab.name" :name="tab.type">
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 地图 -->
      <div class="mapContainer">
        <!-- <div class="tool-tip warning" v-show="isShowWaringTip">
          <span class="icon">
            <el-icon><WarningFilled /></el-icon>
          </span>
          <span>测区不支持交叉面,无法生成航线</span>
        </div> -->
        <div class="tool-tip" v-if="layerParams.addNest">点击地图生成测绘区域</div>
        <div id="layMap" class="ztzf-cesium"></div>
        <leftList
          v-if="
            !layerParams.addNest &&
            !layerParams.editNest &&
            !layerParams.addFolder &&
            !layerParams.editFolder
          "
          @update:coverData="handleCoverDataUpdate"
          @update:deitData="handleEdit"
          @update:editFolder="handleFolder"
          :activeName="activeName"
          @newFencesMethods="newFencesMethods"
        ></leftList>
        <rightEdit
          v-if="layerParams.addNest || layerParams.editNest"
          @callParentMethod="parentMethod"
        ></rightEdit>
        <folderFile
          @refreshMethod="refreshMethod"
          :activeName="activeName"
          v-if="layerParams.addFolder || layerParams.editFolder"
        ></folderFile>
      </div>
    </div>
  </basic-container>
</template>
 
<script setup>
import EventBus from '@/utils/eventBus';
import * as turf from '@turf/turf';
import { dataFolderApi } from '@/api/layer/index';
import folderFile from '@/views/layerManagement/components/folderFile.vue';
import { parseGeoDataToPositions } from '@/utils/geoParseUtil';
import { flyVisual } from '@/utils/cesium/mapUtil';
import rightEdit from '@/views/layerManagement/components/rightEdit.vue';
import leftList from '@/views/layerManagement/components/leftList.vue';
import nationalSpatialPlanning from '@/views/layerManagement/components/nationalSpatialPlanning.vue';
import { DrawPolygon } from '@/views/layerManagement/components/utils';
import * as Cesium from 'cesium';
import { PublicCesium } from '@/utils/cesium/publicCesium';
import _, { cloneDeep, throttle } from 'lodash';
import { ElButton } from 'element-plus';
import { provide } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const userInfo = computed(() => store.getters.userInfo);
const areaCode = userInfo.value?.detail?.areaCode || '';
// console.log('用户信息',areaCode);
// 红色警告交叉面提示窗
const isShowWaringTip = ref(false);
const activeName = ref('电子围栏');
const activeType = ref('0');
let tbJwdList = [];
const selectDataList = ref([]);
// 当前面位置信息
let curPolygonPosition = [];
const tabData = ref([
  {
    name: '电子围栏',
    type: '0',
  },
  {
    name: '自定义禁飞区',
    type: '1',
  },
  {
    name: '国土空间规划',
    type: '2',
  },
]);
const layerParams = ref({
  addNest: false,
  editNest: false,
  editDetailData: null,
  total_count: 0,
  total_area: 0,
  polygonPosition: null,
  decideWhetherToAddOrEdit: null, //新增or编辑围栏
  addAnEditingFolder: null, //新增or编辑文件夹
  addFolder: false,
  editFolder: false,
  folderOption: [], //文件夹选项
  fenceType: 1,
  fenceArea: 0, //围栏面积
  fileType: 1, //文件夹类型
  editFolderData: null,
  editingIsProhibited: false, //禁止编辑
  isDetailShow: false,
});
 
const handleClick = tab => {
  const clickedTab = tabData.value.find(item => item.type === tab.paneName);
  activeType.value = clickedTab.type;
  activeName.value = clickedTab.name;
  getdataFolderApi();
  parentMethod();
};
const refreshMethod = () => {
  getdataFolderApi();
};
const getdataFolderApi = () => {
  let id;
  if (activeName.value === '电子围栏') {
    id = 1;
  } else if (activeName.value === '自定义禁飞区') {
    id = 2;
  } else {
    id = 3;
  }
  dataFolderApi(id).then(res => {
    const originalFolderList = res.data.data || [];
    const formattedFolderOption = originalFolderList.map(folder => ({
      label: folder.name,
      value: folder.id.toString(),
    }));
    layerParams.value.folderOption = formattedFolderOption;
  });
};
// 编辑围栏区域
const handleEdit = val => {
  viewer.entities.removeAll();
  layerParams.value.editDetailData = val;
  drawPolygonExample.editThePatch(true);
  drawPolygonExample.drawTheArea(true);
  const positions = parseGeoDataToPositions(val.geo_data, val.altitude);
  if (positions.length < 3) return; // 少于3个点无法构成多边形
  drawPolygonExample.initPolygon(viewer, positions, true);
};
// 编辑文件夹
const handleFolder = val => {
  layerParams.value.editFolderData = val;
};
// 新增开启绘制
const newFencesMethods = () => {
  viewer.entities.removeAll();
  drawPolygonExample.initHandler(viewer);
  drawPolygonExample.drawTheArea(true);
  drawPolygonExample.startDrawing();
};
// 清除地图数据
const parentMethod = () => {
  drawPolygonExample.delPolygon();
  drawPolygonExample.drawTheArea(false);
  viewer.entities.removeAll();
};
// 点击显示区域
const handleCoverDataUpdate = data => {
  selectDataList.value = data;
  if (selectDataList.value.length > 0) {
    loadDataToMap(selectDataList.value);
  } else {
    viewer.entities.removeAll();
  }
};
const loadDataToMap = dataList => {
  if (!viewer) return;
  viewer.entities.removeAll();
  // 存储所有有效坐标,用于后续定位
  tbJwdList = [];
  dataList.forEach(item => {
    let positions = parseGeoDataToPositions(item.geo_data, item.altitude);
    positions.push(positions[0]);
    if (positions.length < 3) {
      console.warn(`数据 ${item.name} 坐标点不足,无法绘制`);
      return;
    }
    tbJwdList.push(...positions);
    //  转换为 Cesium 所需的 [lng, lat, lng, lat, ...] 扁平数组格式
    let degreesArray = [];
    positions.forEach(pos => {
      degreesArray.push(pos.lng, pos.lat, pos.height);
    });
    viewer.entities.add({
      id: `polygon_${item.id}`,
      customType: 'fence_polygon',
      customInfo: item,
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(
          Cesium.Cartesian3.fromDegreesArrayHeights(degreesArray)
        ),
        material: Cesium.Color.YELLOW.withAlpha(0.5), // 填充色
        outline: true, // 显示边框
        outlineColor: Cesium.Color.YELLOW, // 边框色
        outlineWidth: 2, // 边框宽度
        clampToGround: true, // 贴地显示
      },
 
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(degreesArray),
        width: 2,
        material: Cesium.Color.YELLOW,
        clampToGround: true,
      },
      zIndex: 99, // 层级,确保在其他图层上方显示
    });
  });
  focusOnAllFeatures();
  viewInstance.value?.addLeftClickEvent(null, handleFenceClick);
};
//计算所有图斑的包围球并定位
const focusOnAllFeatures = () => {
  if (tbJwdList.length === 0 || !viewer) return;
 
  // 转换所有经纬度坐标为Cartesian3
  const allPositions = tbJwdList.flatMap(pos =>
    Cesium.Cartesian3.fromDegrees(pos.lng, pos.lat, pos.height || 0)
  );
  if (allPositions.length === 0) return;
  const boundingSphere = Cesium.BoundingSphere.fromPoints(allPositions);
  viewer.camera.flyToBoundingSphere(boundingSphere, {
    duration: 0, // 飞行时间(秒)
    offset: new Cesium.HeadingPitchRange(
      Cesium.Math.toRadians(0), // 方向角
      Cesium.Math.toRadians(-90) // 俯仰角
    ),
  });
};
// 区域点击显示详细信息
const handleFenceClick = movement => {
  if (!viewer) return;
  layerParams.value.editDetailData = null;
  const pickedObject = viewer.scene.pick(movement.position);
  if (Cesium.defined(pickedObject) && pickedObject.id?.customType === 'fence_polygon') {
    const selectedEntity = pickedObject.id;
    const selectedData = selectedEntity.customInfo;
    //   viewer.entities.values.forEach(entity => {
    // if (entity.customType === 'fence_polygon') {
    //   entity.polygon.material = entity === selectedEntity
    //     ? Cesium.Color.RED.withAlpha(0.5)
    //     : Cesium.Color.YELLOW.withAlpha(0.5);
    // }
    // });
    if (activeName.value !== '国土空间规划') {
      layerParams.value.editNest = true; // 显示右侧编辑组件
      layerParams.value.decideWhetherToAddOrEdit = 2; // 标记为编辑模式
      // 根据围栏类型设置fenceType
      if (activeName.value === '电子围栏') {
        layerParams.value.fenceType = 1;
      } else if (activeName.value === '自定义禁飞区') {
        layerParams.value.fenceType = 2;
      }
      layerParams.value.editDetailData = selectedData;
      layerParams.value.fenceArea = selectedData.area;
      layerParams.value.editingIsProhibited = true;
    }
  }
};
let publicCesiumInstance = null;
let viewer = null;
const viewInstance = shallowRef(null);
const homeViewer = shallowRef(null);
 
// 初始化绘制工具实例
const drawPolygonExample = new DrawPolygon();
// 地图初始化
const initMap = () => {
  publicCesiumInstance = new PublicCesium({
    dom: 'layMap',
    flatMode: false,
    terrain: true,
    layerMode: 4,
    contour: false,
  });
 
  viewer = publicCesiumInstance.getViewer();
  viewInstance.value = publicCesiumInstance;
 
  const nanChangPosition = Cesium.Cartesian3.fromDegrees(
    115.892151, // 经度
    28.676493, // 纬度
    15000 // 相机高度
  );
 
  // 执行相机飞行
  viewer.camera.flyTo({
    destination: nanChangPosition,
    duration: 0,
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-90),
      roll: 0,
    },
  });
};
 
// 编辑/绘制
const loadPlanarRoute = async (positions = null, save = false) => {
  isShowWaringTip.value = false;
  if (positions) {
    curPolygonPosition = positions.map(item => {
      let cartographic = Cesium.Cartographic.fromCartesian(item);
      let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
      let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
      let height = Cesium.Math.toDegrees(cartographic.height); //高度
      return {
        lng: _.round(lng, 6),
        lat: _.round(lat, 6),
        height: _.round(height, 6),
      };
    });
  }
 
  let polygon = curPolygonPosition.map(item => [item?.lng, item?.lat]);
  let polygonString = JSON.stringify(polygon);
  layerParams.value.polygonPosition = polygon.length > 0 ? polygonString : null;
  if (polygon.length >= 3) {
    //  确保多边形闭合:最后一个点与第一个点一致(避免计算偏差)
    const firstPoint = polygon[0];
    const lastPoint = polygon[polygon.length - 1];
    const isClosed =
      _.round(firstPoint[0], 6) === _.round(lastPoint[0], 6) &&
      _.round(firstPoint[1], 6) === _.round(lastPoint[1], 6);
    // 若未闭合,手动添加闭合点
    const closedPolygon = isClosed ? polygon : [...polygon, firstPoint];
    //  转换为 turf 支持的 GeoJSON 格式(Polygon 类型需外层嵌套数组)
    const turfPolygon = turf.polygon([closedPolygon]);
    //  计算面积(turf.area() 返回平方米,保留2位小数)
    const area = _.round(turf.area(turfPolygon), 2);
    //  赋值给 layerParams,
    layerParams.value.fenceArea = area;
  } else {
    // 坐标点不足3个时,清空面积
    layerParams.value.fenceArea = 0;
  }
};
drawPolygonExample.subscribe('getShowWaringTip', data => {
  isShowWaringTip.value = data;
});
const throttleLoadPlanarRoute = throttle(loadPlanarRoute, 200);
drawPolygonExample.subscribe('getPolygonPositions', data => {
  throttleLoadPlanarRoute(data);
});
 
// 地图销毁
const destroyMap = () => {
  drawPolygonExample.destroy();
  if (viewer) {
    viewer.destroy();
    viewer = null;
  }
  publicCesiumInstance = null;
};
// 阻止浏览器默认
const preventDefault = event => {
  event.preventDefault();
  return;
};
const cesiumContextMenu = (isAdd = true) => {
  let cesium = document.getElementById('layMap');
  if (!cesium) return;
  if (isAdd) {
    cesium.addEventListener('contextmenu', preventDefault);
  } else {
    cesium.removeEventListener('contextmenu', preventDefault);
  }
};
provide('layerParams', layerParams);
// onMounted(() => {
//   initMap();
//   cesiumContextMenu();
//   getdataFolderApi();
// });
 
// onBeforeUnmount(() => {
//   destroyMap();
//   cesiumContextMenu(false);
// });
onMounted(() => {
  initMap();
  cesiumContextMenu();
  getdataFolderApi();
 
  // 监听单个实体删除事件
  EventBus.on('deleteMapEntityById', deleteMapEntityById);
  // 监听文件夹下所有实体删除事件
  EventBus.on('deleteMapEntitiesByFolderId', deleteMapEntitiesByFolderId);
});
 
onBeforeUnmount(() => {
  destroyMap();
  cesiumContextMenu(false);
 
  // 移除事件监听
  EventBus.off('deleteMapEntityById', deleteMapEntityById);
  EventBus.off('deleteMapEntitiesByFolderId', deleteMapEntitiesByFolderId);
});
 
// 删除单个地图实体
const deleteMapEntityById = entityId => {
  if (!viewer) return;
  const entity = viewer.entities.getById(`polygon_${entityId}`);
  if (entity) {
    viewer.entities.remove(entity);
  }
  // 更新选中数据列表
  selectDataList.value = selectDataList.value.filter(item => item.id !== entityId);
};
 
// 删除文件夹下所有地图实体
const deleteMapEntitiesByFolderId = folderId => {
  if (!viewer) return;
  // 假设围栏数据中包含 folder_id 字段,根据文件夹ID过滤
  const entitiesToDelete = viewer.entities.values.filter(entity => {
    return entity.customInfo?.folder_id === folderId;
  });
  entitiesToDelete.forEach(entity => {
    viewer.entities.remove(entity);
  });
  // 更新选中数据列表
  selectDataList.value = selectDataList.value.filter(item => item.folder_id !== folderId);
};
</script>
 
<style scoped lang="scss">
.layerContainer {
  width: 100%;
  height: 90vh;
}
.mapContainer {
  position: relative;
  width: 100%;
  height: 80vh;
  .warning {
    position: absolute;
    top: 234px;
    color: #fff;
    background: rgba(140, 0, 0, 0.4);
 
    .icon {
      display: flex;
      align-items: center;
      color: #ff1f1f;
    }
  }
  #layMap {
    width: 100%;
    height: 100%;
  }
  .tool-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    width: 800px;
    height: 64px;
    right: 430px;
    top: 60px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-size: 18px;
    color: #ffffff;
 
    background: rgba(11, 31, 58, 0.7);
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
}
</style>