guonan
2025-06-17 be9c1145fc79165142fbe29aacb04dd8e34dd23f
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
<template>
  <div id="gis-view" ref="mapRef"></div>
  <!-- 切换底图影像 -->
  <div
    @click="handleShow"
    class="diqiu"
    :class="{ 'shift-right': simStore.isShowEarth }"
  >
    <img src="@/assets/img/screen/dq.png" alt="" />
  </div>
  <div
    v-show="picShow"
    class="earthBox"
    :class="{ 'shift-right': simStore.isShowEarth }"
  >
    <div
      v-for="(item, index) in views"
      :key="index"
      :class="['item-container', { active: currentIndex === index }]"
      @click="switchView(index)"
    >
      <div class="icon-wrapper">
        <img :src="getImageUrl(item.icon)" :alt="item.label" />
        <span class="label">{{ item.label }}</span>
      </div>
    </div>
  </div>
</template>
 
<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import {
  createPoint,
  initHandler,
  initView,
  addTileset,
  addTerrain,
  removeEntities,
  clearAllPoints,
} from "@/utils/map.js";
import { loadAreaPolygon } from "@/utils/area.js";
import { loadAreaPolygonAll } from "@/utils/area_all.js";
import { isVisibleDistance } from "@/utils/customEntity";
import { useRoute } from "vue-router";
import { EventBus } from "@/eventBus"; // 引入事件总线
import { useSimStore } from "@/store/simulation";
const route = useRoute();
const simStore = useSimStore();
 
import {
  getDangerPoint,
  getDeviceInfo,
  getAeraCode,
  getAeraTownCode,
  getDeviceCount,
} from "@/api/hpApi";
/////////////////////////地图影像选择/////////////////////////
const views = [
  { label: "地图", value: "map", icon: "地图.png" },
  { label: "影像", value: "image", icon: "影像.png" },
  { label: "地形", value: "terrain", icon: "地形.png" },
];
 
const getImageUrl = (iconName) => {
  return `/images/earth/${iconName}`;
};
 
const picShow = ref(false);
 
const handleShow = () => {
  picShow.value = !picShow.value;
};
 
const currentIndex = ref(-1);
 
let currentLayer = null;
 
const switchView = async (index) => {
  currentIndex.value = index;
 
  // 如果已经有图层存在,先从地图中移除
  if (currentLayer) {
    currentLayer.removeFromMap();
    currentLayer = null; // 清空引用
  }
 
  if (views[index].value === "map") {
    // 百度地图
    currentLayer = await earthCtrl.factory.createImageryLayer({
      sourceType: "baidu",
      url: "https://ss1.bdstatic.com/8bo_dTSlR1gBo1vgoIiO_jowehsv/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl&udt=20180810&scaler=1&showtext=1",
    });
  } else if (views[index].value === "image") {
    currentLayer = await earthCtrl.factory.createImageryLayer({
      sourceType: "mapworld",
      url: "https://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=3ec79cf7a9dcc6bb18411a5414b148cb",
      layers: "tdtBasicLayer",
      style: "default",
      format: "image/jpeg",
      maximumLevel: 18,
      layer: "",
      tileMatrixSetID: "",
    });
    //标注层
    currentLayer = await earthCtrl.factory.createImageryLayer({
      sourceType: "mapworld",
      subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
      url: "https://{s}.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&tk=c53eb074c3fcba5ac86103d4d711bbe8",
    });
  } else if (views[index].value === "terrain") {
    // 地形图层
    currentLayer = await earthCtrl.factory.createTerrainLayer({
      sourceType: "arcgis",
      url: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer",
    });
  }
};
/////////////////////////地图影像选择/////////////////////////
 
let handler = null;
/////////////////////////初始化地图/////////////////////////
function initMap() {
  window.Cesium = SmartEarth.Cesium;
  window.earthCtrl = new SmartEarth.EarthCtrl("gis-view");
  window.viewer = earthCtrl.viewer;
 
  // 1. 设置初始时间
  const date = new Date(2025, 3, 11, 12, 0, 0, 0);
  const julianDate = SmartEarth.Cesium.JulianDate.fromDate(date);
 
  // 2. 配置时钟选项
  earthCtrl.viewer.clockViewModel.shouldAnimate = false;
  earthCtrl.viewer.clockViewModel.clockRange =
    SmartEarth.Cesium.ClockRange.CLAMPED;
  earthCtrl.viewer.clockViewModel.multiplier = 0;
  earthCtrl.viewer.clock.currentTime = julianDate;
 
  // 显示fps
  earthCtrl.showFPS = true;
 
  // 先添加底图
  earthCtrl.factory.createImageryLayer({
    sourceType: "mapworld",
    url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=7eb11c0c503429878691ac917238f87f",
    layers: "tdtBasicLayer",
    style: "default",
    format: "image/jpeg",
    maximumLevel: 18,
  });
}
 
/////////////////////////新建方案区域选择/////////////////////////
const MULTIPOLYGON_COORDS = ref([]);
let previousEntities = []; // 用于存储之前创建的实体
const flyToHeight = ref(null);
const ShowFill = ref(true);
 
// 监听新建方案选择的区域范围
EventBus.on("select-geom", ({ geom, flyHeight, shouldShowFill }) => {
  flyToHeight.value = flyHeight;
  ShowFill.value = shouldShowFill;
  const coordsStr = geom
    .replace("MULTIPOLYGON(((", "") // 去掉开头
    .replace(")))", ""); // 去掉结尾
 
  // 分割成 ["lon lat", "lon lat", ...]
  const coordPairs = coordsStr.split(",");
 
  // 转换为 [[[lon, lat], [lon, lat], ...]] 格式
  MULTIPOLYGON_COORDS.value = [
    coordPairs.map((pair) => {
      const [lon, lat] = pair.trim().split(" ").map(Number);
      return [lon, lat];
    }),
  ];
 
  // 检查是否是空多边形,如果是空,则去掉面片颜色,并飞回初始位置
  if (geom === "MULTIPOLYGON EMPTY") {
    clearPreviousEntities();
    flyToHomeView();
    return; // 不执行后续操作
  }
 
  // 清除之前的所有实体
  clearPreviousEntities();
  // 选中区域标色
  addCustomPolygon(ShowFill.value);
});
 
// 清除之前的所有实体
function clearPreviousEntities() {
  previousEntities.forEach((entity) => {
    viewer.entities.remove(entity);
  });
  previousEntities = [];
}
 
// 计算选中区域中心点
function calculateCenter(coordinates) {
  const lons = coordinates.flat().map((coord) => coord[0]);
  const lats = coordinates.flat().map((coord) => coord[1]);
  return {
    lon: (Math.min(...lons) + Math.max(...lons)) / 2,
    lat: (Math.min(...lats) + Math.max(...lats)) / 2,
  };
}
 
function convertToGeoJson(coords) {
  return {
    type: "Feature",
    id: 0,
    bbox: calculateCenter(MULTIPOLYGON_COORDS.value), // 可选
    properties: {
      center: calculateCenter(MULTIPOLYGON_COORDS.value), // 第一个点作为 center
      centroid: MULTIPOLYGON_COORDS.value[0][0], // 可选
      level: "district",
      code: 123456,
      districtCount: 0,
    },
    geometry: {
      type: "MultiPolygon",
      coordinates: [coords], // 包装成 MultiPolygon
    },
  };
}
 
function addCustomPolygon(ShowFill = true) {
  // 将 MULTIPOLYGON_COORDS.value 转换为 GeoJSON 格式
  const geoJson = convertToGeoJson(MULTIPOLYGON_COORDS.value);
  const center = geoJson.properties.center;
 
  // 创建多边形实体,并根据 ShowFill 参数决定是否显示填充颜色
  const polygonEntity = viewer.entities.add({
    polygon: {
      hierarchy: Cesium.Cartesian3.fromDegreesArray(
        geoJson.geometry.coordinates[0][0].flat()
      ),
      material: ShowFill
        ? Cesium.Color.RED.withAlpha(0.3) // 半透明红色填充
        : new Cesium.ColorMaterialProperty(Cesium.Color.TRANSPARENT), // 如果不需要填充,则使用透明材质
      outline: true,
      outlineColor: Cesium.Color.RED, // 红色边框
      outlineWidth: 5,
      clampToGround: true, // 贴地显示
    },
  });
 
  previousEntities.push(polygonEntity);
 
  // 飞向中心点
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      center.lon,
      center.lat,
      flyToHeight.value
    ), // 提高到指定高度
    orientation: {
      heading: Cesium.Math.toRadians(0), // 正北方向
      pitch: Cesium.Math.toRadians(-90), // 向下倾斜90度(垂直俯视)
      roll: 0.0,
    },
  });
}
 
EventBus.on("close-selectArea", () => {
  clearPreviousEntities();
  flyToHomeView();
});
/////////////////////////新建方案区域选择/////////////////////////
 
function addCityPolygon() {
  const url = `/json/110000.geo.json`;
  let wallLayer = earthCtrl.factory.createTrailWallLayer({
    url: "/json/110000.geojson",
    color: "LIGHTSTEELBLUE", //颜色
    height: 2000, //高度
    speed: 3,
  });
  const dataSourcePromise = Cesium.GeoJsonDataSource.load(url, {
    clampToGround: true,
  });
  return dataSourcePromise.then(function (dataSource) {
    viewer.dataSources.add(dataSource);
    // 所有的数据
    const polygonEntity = dataSource.entities.values;
    const distanceDisplayCondition = new Cesium.DistanceDisplayCondition(
      1000,
      50000000
    );
    polygonEntity.forEach((entity) => {
      entity.polygon.material = new Cesium.ColorMaterialProperty(
        Cesium.Color.LIGHTSTEELBLUE.withAlpha(0)
        // new Cesium.Color.fromCssColorString("#0f2636b3")
        // Cesium.Color.fromRandom({
        //     alpha: 0.5,
        //     minimumAlpha: 0.2,
        //     maximumAlpha: 0.9,
        // })
      );
 
      entity.polygon.distanceDisplayCondition = distanceDisplayCondition;
 
      const properties = entity.properties;
      const center = properties.centroid.getValue();
      const fullname = properties.fullname.getValue();
      const districtCount = properties.districtCount.getValue() || 0;
 
      const position = Cesium.Cartesian3.fromDegrees(center[0], center[1]);
      const positions = entity.polygon.hierarchy._value.positions;
 
      entity.position = position;
      // 判断是否为东城区或西城区
      let labelText = fullname || "默认标签";
      if (fullname === "东城区" || fullname === "西城区") {
        // 将文本拆分为竖列
        labelText = fullname.split("").join("\n");
      }
      entity.label = {
        // 文本。支持显式换行符“ \ n”
        text: labelText,
        // 字体样式,以CSS语法指定字体
        font: "22pt Source Han Sans CN",
        // 字体颜色
 
        fillColor: Cesium.Color.fromCssColorString("#FD9B00"),
        // 背景颜色
        backgroundColor: Cesium.Color.BLACK.withAlpha(0.8),
        // 是否显示背景颜色
        showBackground: false,
        // 字体边框
        outline: true,
        // 字体边框颜色
        outlineColor: Cesium.Color.WHITE,
        // 字体边框尺寸
        outlineWidth: 0,
        // 应用于图像的统一比例。比例大于会1.0放大标签,而比例小于会1.0缩小标签。
        scale: 1.0,
        scaleByDistance: new Cesium.NearFarScalar(1.5e2, 1.0, 1.5e7, 0.5),
        // 设置样式:FILL:填写标签的文本,但不要勾勒轮廓;OUTLINE:概述标签的文本,但不要填写;FILL_AND_OUTLINE:填写并概述标签文本。
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        // 相对于坐标的水平位置
        verticalOrigin: Cesium.VerticalOrigin.CENTER,
        // 相对于坐标的水平位置
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
        pixelOffset: new Cesium.Cartesian2(0, 0),
        // pixelOffset: new Cesium.Cartesian2(0, 0),
        // 显示在距相机的距离处的属性,多少区间内是可以显示的
        distanceDisplayCondition: distanceDisplayCondition,
        // : new Cesium.DistanceDisplayCondition(0, 50000),
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
        // 是否显示
        show: true,
      };
      entity.polyline = {
        positions: positions,
        width: 5,
        material: new Cesium.ColorMaterialProperty(
          Cesium.Color.SKYBLUE.withAlpha(0.9)
          // Cesium.Color.fromRandom({
          //     alpha: 0.5,
          //     minimumAlpha: 0.2,
          //     maximumAlpha: 0.9,
          // })
        ),
        clampToGround: true,
        distanceDisplayCondition: distanceDisplayCondition,
      };
 
      viewer.entities.add(entity);
    });
 
    // 获取 GeoJSON 中的第一个 Polygon feature
  });
}
 
function flyToHomeView() {
  const view = {
    destination: {
      x: -2355432.569004413,
      y: 4687573.191838412,
      z: 4098726.315265574,
    },
    orientation: {
      pitch: -0.9541030830183503,
      roll: 0.00031421159527500464,
      heading: 6.140424766644804,
    },
  };
  viewer.scene.camera.flyTo(view);
}
 
///////////////////////// 区域标记点管理系统 /////////////////////////
// 存储所有创建的HTML实体(地图上的标记点)
const htmlEntityList = [];
 
// 统一管理所有区域标记的样式配置
const ENTITY_CONFIG = {
  label: {
    backgroundColor: SmartEarth.Cesium.Color.SKYBLUE.withAlpha(0.8),
    font: "14pt Source Han Sans CN",
    fillColor: SmartEarth.Cesium.Color.WHITE,
    showBackground: true,
  },
  showBillboard: false,
  showLabel: true,
};
 
// 区域级别配置
const LEVEL_CONFIG = {
  // 二级区域
  secondary: {
    maxVisibleDistance: 69000,
    minVisibleDistance: 20000,
    flyToHeight: 12000,
  },
  // 一级区域
  primary: {
    maxVisibleDistance: 60000000,
    minVisibleDistance: 70000,
    flyToHeight: 45000,
  },
};
 
// 初始化区域统计
async function initDistrictCount(level = "secondary") {
  try {
    const deviceAreaTotal = ref([]);
    const deviceTownTotal = ref([]);
 
    if (level === "primary") {
      // 一级区域处理
      if (route.path === "/zhjc") {
        deviceAreaTotal.value = await getDeviceCount(); // 获取区级设备统计
      }
 
      const res = await getAeraCode();
      res.data.forEach((item) => {
        if (route.path === "/zhjc") {
          const matchedDistrict = deviceAreaTotal.value.data?.find(
            (d) => d.districtName === item.districtName
          );
          if (matchedDistrict) {
            item.count = matchedDistrict.count; // 更新 count
          }
        }
        processDistrictItem(item, LEVEL_CONFIG[level], level);
      });
    } else if (level === "secondary") {
      // 二级区域处理
      const primaryRes = await getAeraCode();
 
      if (route.path === "/zhjc") {
        // 并发获取每个区的设备统计
        deviceTownTotal.value = await Promise.all(
          primaryRes.data.map((item) =>
            getDeviceCount({ districtCode: Number(item.districtCode) })
          )
        );
      }
 
      // 并发获取每个区下的镇数据
      const townResults = await Promise.all(
        primaryRes.data.map((item) => getAeraTownCode(item.districtCode))
      );
 
      // 处理每个区的镇数据
      for (let i = 0; i < townResults.length; i++) {
        const townRes = townResults[i];
        const deviceCountData = deviceTownTotal.value[i]?.data || []; // 对应区的设备统计数据
 
        townRes.data.forEach((townItem) => {
          if (route.path === "/zhjc") {
            const matchedTown = deviceCountData.find(
              (d) => d.districtName === townItem.districtName
            );
            if (matchedTown) {
              townItem.count = matchedTown.count;
            }
          }
          processDistrictItem(townItem, LEVEL_CONFIG[level], level);
        });
      }
    } else {
      console.error("未知的 level 类型:", level);
    }
  } catch (error) {
    console.error(`初始化 ${level} 级区域统计失败:`, error);
  }
}
// 处理单个区域项
function processDistrictItem(item, config, level = "secondary") {
  // 添加默认值
  normalizeItemData(item);
  const html = createDistrictHtmlMarker(item, config);
 
  if (level === "secondary") {
    secondaryHandler(html, item, config);
  } else {
    primaryHandler(html, item, config);
  }
 
  // 此处必须加,不然二次调用初始化函数的时候会将一二级区域所有的点都显示在页面上
  html.show = isVisibleDistance(
    config.minVisibleDistance,
    config.maxVisibleDistance
  );
 
  htmlEntityList.push(html);
}
import { ElMessage } from "element-plus";
 
const districtList = ref([]);
 
// 设置二级区域点击处理(请求隐患点,监测设备等)
function secondaryHandler(html, item, config) {
  html.element.addEventListener("click", async () => {
    try {
      // 清理已有点
      handleCleanup();
 
      // 显示 loading 提示(无遮罩,仅文字+转圈)
      const loadingInstance = ElMessage({
        type: "info",
        message: "数据正在加载中...",
        duration: 0, // 持续显示,直到手动关闭
        icon: "loading", // 显示为 loading 图标(Element Plus 支持)
        grouping: true, // 相同内容的消息合并,避免重复提示
      });
 
      let res;
      if (route.path === "/yhgl") {
        // 请求隐患点数据
        res = await getDangerPoint(item.districtCode);
      } else if (route.path === "/zhjc") {
        // 请求监测设备数据
        res = await getDeviceInfo(null, item.districtCode);
      } else {
        loadingInstance.close();
        return;
      }
      districtList.value = [];
      // 更新数据
      districtList.value = res.data.pageData;
 
      if (districtList.value.length === 0) {
        ElMessage.warning("该区域暂无相关数据");
        loadingInstance.close();
        return;
      }
 
      // 创建地图点
      for (const [index, point] of districtList.value.entries()) {
        point.id = point.hdId || point.deviceId; // 根据实际情况调整
        point.latitude = point.lat || point.latitude; // 根据实际情况调整
        point.longitude = point.lon || point.longitude; // 根据实际情况调整
        point.showBillboard = true;
        point.type = point.disasterType || point.deviceTypeName; // 根据实际情况调整
        point.className = "district";
 
        // ✅ 根据路由决定名称字段
        if (route.path === "/yhgl") {
          point.name = point.hdName; // 隐患点名称
          point.className = "district";
        } else if (route.path === "/zhjc") {
          point.name = point.deviceName; // 设备简称
          point.className = "device";
        }
 
        await createPoint(point);
      }
 
      // 飞向指定位置
      await flyToDistrict(item.longitude, item.latitude, config.flyToHeight);
 
      // 加载完成后关闭 loading 提示
      loadingInstance.close();
    } catch (error) {
      console.error("区域点击处理失败:", error);
      ElMessage.error("数据加载失败,请稍后再试");
      loadingInstance.close(); // 确保在发生错误时也关闭 loading 提示
    }
  });
}
 
const handleCleanup = async () => {
  districtList.value = [];
  clearAllPoints();
};
 
// 设置一级区域点击处理
function primaryHandler(html, item, config) {
  html.element.addEventListener("click", () => {
    flyToDistrict(item.longitude, item.latitude, config.flyToHeight);
  });
}
 
// 统一数据格式和添加默认配置
function normalizeItemData(item) {
  item.name = `${item.districtName}\n${item.count}`;
  item.longitude = item.lon;
  item.latitude = item.lat;
  Object.assign(item, ENTITY_CONFIG);
}
 
// 创建HTML标记
function createDistrictHtmlMarker(item, config) {
  const html = earthCtrl.view.createScreenDialog({
    html: `
      <div class="district-count">
        <div class="name">${item.districtName}</div>
        <div class="value">${item.count}</div>
      </div>
    `,
    lon: item.lon,
    lat: item.lat,
    height: 0,
  });
 
  html.maxVisibleDistance = config.maxVisibleDistance;
  html.minVisibleDistance = config.minVisibleDistance;
 
  return html;
}
 
// 飞向指定区域
function flyToDistrict(longitude, latitude, height) {
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, height),
    orientation: {
      pitch: Cesium.Math.toRadians(-90),
      heading: Cesium.Math.toRadians(0),
      roll: 0,
    },
    duration: 2,
  });
}
 
// 在路由监听器中
const validPaths = ["/", "/yhgl", "/zhjc"];
 
watch(
  () => route.fullPath,
  (val) => {
    const isValidPath = validPaths.includes(val);
 
    // 控制相机变化监听
    if (isValidPath) {
      initAllDistrictCounts();
      handleCameraChange();
      // 控制HTML实体显示
      htmlEntityList.forEach((item) => {
        item.show = isValidPath
          ? isVisibleDistance(item.minVisibleDistance, item.maxVisibleDistance)
          : false;
      });
    } else {
      htmlEntityList.forEach((item) => {
        item.show = false;
      });
      removeCameraChange();
    }
  }
);
 
let cameraChangeTimer = null;
 
function toggleHtmlLayerByVisibleDistance() {
  if (cameraChangeTimer) {
    clearTimeout(cameraChangeTimer);
    cameraChangeTimer = null;
    return;
  }
 
  cameraChangeTimer = setTimeout(() => {
    // 更新HTML实体显示状态
    htmlEntityList.forEach((item) => {
      item.show = isVisibleDistance(
        item.minVisibleDistance,
        item.maxVisibleDistance
      );
    });
  }, 100);
}
 
function handleCameraChange() {
  viewer.camera.changed.addEventListener(toggleHtmlLayerByVisibleDistance);
}
 
function removeCameraChange() {
  viewer.camera.changed.removeEventListener(toggleHtmlLayerByVisibleDistance);
}
 
// 初始化函数
function initAllDistrictCounts() {
  initDistrictCount("primary"); // 一级区域
  initDistrictCount("secondary"); // 二级区域
}
 
onMounted(() => {
  initMap();
  addCityPolygon();
  initHandler();
  // initView()
  // loadAreaPolygon("/json/nsl_area.geojson");
  // loadAreaPolygonAll("/json/geometry.json", true);
  flyToHomeView();
  // 页面加载时初始化
  initAllDistrictCounts();
  handleCameraChange();
  // 设置 billboard 点击事件
});
onUnmounted(() => {
  removeCameraChange();
  EventBus.off("select-geom");
  EventBus.off("close-selectArea");
});
</script>
 
<style lang="less" scoped>
#gis-view {
  width: 100vw;
  height: 100vh;
  position: absolute;
}
 
// // 修改指南针位置
/deep/ .compass {
  right: 128px !important;
  top: 112px;
}
 
.diqiu {
  position: absolute;
  bottom: 8%;
  right: 4%;
  z-index: 9999;
}
 
.earthBox {
  z-index: 9999;
  width: 12%;
  height: 7%;
  background-color: rgba(0, 9, 9, 0.3);
  position: absolute;
  right: 8%;
  bottom: 6%;
  display: flex;
  justify-content: space-evenly;
  padding: 10px 6px;
}
 
.icon-wrapper {
  position: relative;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  border: 1px solid transparent; /* 默认透明边框占位 */
 
  img {
    height: 100%;
    width: auto; /* 确保图片按比例缩放 */
    margin: 0;
    padding: 0;
    display: block; /* 移除图片下方可能存在的空白间隙 */
  }
 
  .label {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.5);
    text-align: center;
    color: white;
  }
}
 
.item-container {
  position: relative;
  display: inline-block;
  cursor: pointer;
}
 
.item-container.active .icon-wrapper {
  border: 1px solid #218967; /* 蓝色边框 */
}
 
.item-container.active .label {
  background-color: rgba(33, 137, 103, 0.8);
}
 
.diqiu.shift-right {
  right: 10%;
}
.earthBox.shift-right {
  right: 13%;
}
</style>