wangjuncheng
2025-04-17 2ee0ab96f3edfbf8aefc9e2c5d5f73332411eb99
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
// import Canvas2Image from "./Canvas2Image.js"
// import cameraIcon from "../assets/images/base/视频测点.png"
// import cameraIconSel from "../assets/images/base/视频测点sel.png"
import { ElLoading, ElMessage } from "element-plus";
import RainEffect from './rain'
import SnowEffect from './snow'
let layerIsOpen = false;
const Cesium = SmartEarth.Cesium;
const colorAll = {
  point: Cesium.Color.fromCssColorString("#ff0000"),
  polyline: Cesium.Color.fromCssColorString("#ffff0050"),
  polygon: Cesium.Color.fromCssColorString("#ffff0050"),
};
 
const mapUtils = {
  earthCtrl: null,
  // 是否开始时序化展示
  timeShow: false,
  CurrentClickedGlb: null,
  viewShedTool: null,
  analysisDXPMRes: [],
  slopeArrow: null,
  elevationTool: null,
  rainEffect: null,
  snowEffect: null, // 新增雪效果实例
 
  init(earthCtrl) {
    this.earthCtrl = earthCtrl;
    return this;
  },
  hexToColor(hexColor) {
    const hex = hexColor.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16) / 255;
    const g = parseInt(hex.substring(2, 4), 16) / 255;
    const b = parseInt(hex.substring(4, 6), 16) / 255;
    return new Cesium.Color(r, g, b, 1.0);
  },
  // 清除天气特效
  delRain(){
    if (this.rainEffect) {
      this.rainEffect.destroy()
      this.rainEffect = null
    }
  },
  delSnow(){
    if (this.snowEffect) {
      this.snowEffect.destroy();
      this.snowEffect = null;
    }
  },
  // 雨天模拟
  toggleRain(option, show) {
    console.log(option, 'option')
    // 先销毁旧实例
    if (this.rainEffect) {
      this.rainEffect.destroy()
      this.rainEffect = null
    }
    this.rainEffect = new RainEffect(earthCtrl.viewer, {
      tiltAngle: -0.2, //倾斜角度
      rainSize: option.rainSize, // 雨的大小
      rainSpeed: option.rainSpeed, // 雨的速度
      color: this.hexToColor(option.rainColor)  // 雨的颜色
    })
  },
  // 雪天模拟
  toggleSnow(option = {}, show = true) {
    console.log(option, 'option');
    const defaultOption = {
      snowSize: 0.02, // 默认雪的大小
      snowSpeed: 100.0, // 默认雪的速度
      snowColor: "#ffffff", // 默认颜色:白色
    };
    option = { ...defaultOption, ...option };
    if (this.snowEffect) {
      this.snowEffect.destroy();
      this.snowEffect = null;
    }
    this.snowEffect = new SnowEffect(earthCtrl.viewer, {
      snowSize: option.snowSize, // 雪的大小
      snowSpeed: option.snowSpeed, // 雪的速度
      snowColor: this.hexToColor(option.snowColor), // 雪的颜色
    });
 
    // 控制显示/隐藏
    if (this.snowEffect) {
      this.snowEffect.show(show);
    }
  },
  // 坡度分析
  pdfx(option) {
    this.elevationTool = new SmartEarth.ElevationTool(earthCtrl)
    if (option.terrainRender == '1') {
      this.elevationTool.type = 'slope'
    } else {
      this.elevationTool.type = 'none'
    }
    this.elevationTool.tf = option.contourLines
    this.elevationTool.setSpacing(option.spacing)
    this.elevationTool.setWidth(option.lineWidth)
    this.elevationTool.setContourColor(option.color);
    this.elevationTool.render();
    console.log(this.elevationTool, 'eleelelelelelelel')
  },
  // 坡向箭头
  pxjt(colors, angles) {
    this.slopeArrow = earthCtrl.factory.createSlopeArrow({});
    this.slopeArrow.setColorsAndAngles(colors, angles);
 
    // 创建绘制工具
    const drawTool = earthCtrl.shapeTool.createDrawShapeTool((e) => {
      const polygonI = [];
      const polygonPosition = [];
      for (const i of e.result) {
        const ellipsoid = earthCtrl.coreMap.scene.globe.ellipsoid;
        const cartographic = ellipsoid.cartesianToCartographic(i);
 
        const lon = Cesium.Math.toDegrees(cartographic.longitude);
        const lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
        polygonI.push(lon, lat, 0);
        polygonPosition.push(lon, lat);
      }
      const PolygonArr = [];
      PolygonArr.push({
        id: earthCtrl.factory.createUUID(),
        polygon: polygonI,
      });
 
      // 清除绘制工具
      drawTool.removeFromMap();
      // 设置坡度箭头的位置和类型
      this.slopeArrow.setPositions(polygonPosition);
      this.slopeArrow.setSlopeType(1);
      this.slopeArrow.setRegionEnabled(true);
      console.log(this.slopeArrow, 'slope')
    });
  },
  // 关闭坡向箭头
  gbpxjt() {
    if (this.slopeArrow) {
      this.slopeArrow.setSlopeType(0);
    }
  },
  // 标绘
  CreateLabel(pic, show) {
    if (show) {
      earthCtrl.factory.createSimpleGraphic(pic, {}, function (entity) {
        console.log(entity, "entity");
        window.Viewer = earthCtrl.viewer
        //开启编辑并启用属性弹窗
        earthCtrl.factory.SimpleGraphic.edit(true, {
          editProp: true,
          showRightButton: false,
        });
      });
    }
  },
  //标绘清除
  del() {
    earthCtrl.factory.SimpleGraphic.clear();
  },
 
  //  水平测量
  spjl() {
    earthCtrl.measure.horizontalDistance(colorAll, (e) => {
      console.log(e);
    }).onEnd = () => {
      console.log("水平测距已完成");
    };
  },
  //直线测量
  jl() {
    earthCtrl.measure.lineDistance(colorAll, (e) => {
      console.log(e)
    }).onEnd = () => {
      console.log("直线测量已完成");
    };
  },
  // 垂直测量
  czgd() {
    earthCtrl.measure.height(colorAll, (e) => {
      console.log(e);
    }).onEnd = () => {
      console.log("垂直测距已完成");
    };
  },
  //面积测量
  mjcl() {
    earthCtrl.measure.surfaceArea({
      ...colorAll,
      tin: true, // 是否显示tin三角网
      onlyTerrain: false // 是否只测量精细地形
    }, (e) => {
      console.log(e)
 
    }).onEnd = () => {
      console.log('面积测量已完成')
    }
  },
  // 清除测量
  clear() {
    earthCtrl.measure.clearResult()
  },
  syfx(option) {
    this.viewShedTool = earthCtrl.analysis.createViewShed({
      heading: option.heading,
      distance: option.distance,
      horizontalViewAngle: option.horizontalViewAngle,
      verticalViewAngle: option.verticalAngle,
      size: 1024,
      visibleAreaColor: SmartEarth.Cesium.Color.GREEN.withAlpha(1),
      invisibleAreaColor: SmartEarth.Cesium.Color.RED.withAlpha(1),
      height: 1,
    });
  },
  // 鼠标绘制可视域
  syfxByClick(option, callback) {
    if (!this.viewShedTool) {
      this.syfx(option);
    }
    this.viewShedTool.mouseCreate().then((res) => {
      callback(res);
    });
  },
  changeSyfx(option) {
    if (!this.viewShedTool) {
      this.syfx(option);
    }
    this.viewShedTool.updateParameters(option);
  },
  showSyfxViewCone(isShow) {
    if (this.viewShedTool) {
      this.viewShedTool.visualCone = isShow;
    }
  },
  syfxqc(option) {
    if (!this.viewShedTool) {
      this.syfx(option);
    }
    this.viewShedTool.removeFromMap();
  },
  // 绘制剖面
  pmtq(distance) {
    let analysisDXPM = earthCtrl.analysis.createProfile({
      defaultChars: true,
      step: distance || 60, // 如果未提供距离,默认为60
      image: SmartEarthRootUrl + "Workers/image/result_red.png",
      echartsView: "echartsView1",
      echartsParentView: "sectionCharts",
      callback: function (e) {
        console.info(e);
      },
    });
 
    analysisDXPM.drawPolyLine({ skipClick: true });
    this.analysisDXPMRes.push(analysisDXPM); // 存储结果以供清除
  },
 
  // 清除剖面
  handleClear() {
    for (let i = 0; i < this.analysisDXPMRes.length; i++) {
      let res = this.analysisDXPMRes[i];
      if (res) {
        res.removeFromMap();
      }
    }
    this.analysisDXPMRes = []; // 清空存储的结果
  },
  jdcl() {
    this.earthCtrl.measure.angle(
      {
        point: Cesium.Color.fromCssColorString("#ff0000"),
        polyline: Cesium.Color.fromCssColorString("#ffff0050"),
        polygon: Cesium.Color.fromCssColorString("#ffff0050"),
      },
      (e) => { }
    );
  },
  qxcl() {
    this.earthCtrl.measure.measureSlope(
      {
        point: Cesium.Color.fromCssColorString("#ff0000"),
        polyline: Cesium.Color.fromCssColorString("#ffff0050"),
        polygon: Cesium.Color.fromCssColorString("#ffff0050"),
      },
      (e) => { }
    );
  },
  fwjcl() {
    this.earthCtrl.measure.azimuth(
      {
        point: Cesium.Color.fromCssColorString("#ff0000"),
        polyline: Cesium.Color.fromCssColorString("#ffff0050"),
        polygon: Cesium.Color.fromCssColorString("#ffff0050"),
      },
      (e) => { }
    );
  },
  // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>场景截图<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  photoshut() {
    var canvas = earthCtrl.viewer.scene.canvas;
    var imageWidth = 800;
    var img = Canvas2Image.convertToImage(
      canvas,
      imageWidth,
      (imageWidth * canvas.height) / canvas.width,
      "png"
    );
    var loadImg = document.createElement("a");
    loadImg.href = img.src;
    loadImg.download = "Screenshots";
    loadImg.click();
  },
  // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>空间分析<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  volumetricResults: [],
  viewThrough: null,
  skyline: null,
  viewShedTool: null,
  RestrictTheHeight: null,
  Buffers: [],
  primitiveCollection: null,
  polygonInstaceArr: [],
  outlineInstanceArr: [],
  loadingService: null,
  movingViewShed: null,
  movingCircleViewshed: null,
  time: null,
  flfx() {
    ElMessage({
      message: "已开启挖填方计算功能,再次点击关闭",
    });
    let volumetric = earthCtrl.analysis.createVolumetricMeasure({});
    volumetric.startDrawing();
    this.volumetricResults.push(volumetric);
  },
  tsfx() {
    this.viewThrough = this.earthCtrl.analysis.createViewThrough({ height: 1 });
  },
  tjxfx() {
    this.skyline = this.earthCtrl.analysis.createSkyline({
      color: SmartEarth.Cesium.Color.fromCssColorString("#ff0"),
      width: 3,
    });
  },
  wgfx() {
    let turf = Cesium.turf;
    this.clearWgfx();
    this.earthCtrl.factory.createSimpleGraphic(
      "polygon",
      { showSize: false, removeEdit: true },
      (entity) => {
        let postitions = entity.polygon.hierarchy
          .getValue()
          .positions.reduce((obj, cur) => {
            let lonlat = this.cartesainToDegrees(cur);
            obj.push([lonlat.lng, lonlat.lat]);
            return obj;
          }, []);
        //多变形闭环
        postitions.push(postitions[0]);
        let gridRadius = 0.05;
        let polygon = turf.polygon([postitions]);
        //获取多边形bbox
        let bbox = turf.bbox(polygon);
        //初始化数组
        this.polygonInstaceArr = [];
        this.outlineInstanceArr = [];
        //加载
        this.loadingService = ElLoading.service({
          lock: true,
          text: "正在计算网格...",
          background: "rgba(0, 0, 0, 0.7)",
        });
        if (!this.primitiveCollection)
          this.primitiveCollection = window.viewer.scene.primitives.add(
            new Cesium.PrimitiveCollection()
          );
        let hexres = turf.squareGrid(bbox, gridRadius, {
          units: "kilometers",
          mask: polygon,
        });
        if (hexres.features.length == 0) {
          ElMessage({
            message: "半径过大,无法计算",
          });
          this.loadingService.close();
          entity.deleteObject();
          return;
        }
        if (hexres.features.length > 500000) {
          ElMessage({
            message: "网格数量过大,请缩小半径",
          });
          this.loadingService.close();
          entity.deleteObject();
          return;
        }
        hexres.features.forEach((item, index) => {
          if (turf.booleanContains(polygon, item)) {
            let newArr = item.geometry.coordinates[0].map((el) => {
              return Cesium.Cartesian3.fromDegrees(el[0], el[1]);
            });
            //网格面
            this.polygonInstaceArr.push(
              new Cesium.GeometryInstance({
                geometry: new Cesium.PolygonGeometry({
                  polygonHierarchy: new Cesium.PolygonHierarchy(newArr),
                }),
              })
            );
            //轮廓线
            this.outlineInstanceArr.push(
              new Cesium.GeometryInstance({
                geometry: new Cesium.GroundPolylineGeometry({
                  //贴地线几何
                  positions: newArr,
                  width: 1.5,
                }),
              })
            );
          }
        });
        let temPri = new Cesium.GroundPrimitive({
          geometryInstances: this.polygonInstaceArr, //可以是实例数组
          appearance: new Cesium.MaterialAppearance({
            material: Cesium.Material.fromType("Color", {
              color: Cesium.Color.fromCssColorString("#0032ff").withAlpha(0.2),
            }),
          }),
        });
        let outlinePrimitive = new Cesium.GroundPolylinePrimitive({
          //贴地primitive线
          geometryInstances: this.outlineInstanceArr,
          appearance: new Cesium.PolylineMaterialAppearance({
            material: Cesium.Material.fromType(Cesium.Material.ColorType, {
              color: Cesium.Color.fromCssColorString("#0032ff"), //线条颜色
              // gapColor:Cesium.Color.TRANSPARENT, //间隔颜色
              // dashLength: 15, //短划线长度
            }),
          }),
        });
        this.primitiveCollection.add(temPri);
        this.primitiveCollection.add(outlinePrimitive);
        this.loadingService.close();
        entity.deleteObject();
        entity = null;
      }
    );
  },
  clearWgfx() {
    this.primitiveCollection && this.primitiveCollection.removeAll();
    this.polygonInstaceArr = [];
    this.outlineInstanceArr = [];
    if (this.loadingService) {
      this.loadingService.close();
      this.loadingService = null;
    }
  },
  ServerUnion() {
    let turf = Cesium.turf;
  },
  cartesainToDegrees(cartesian) {
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var cartographic = ellipsoid.cartesianToCartographic(cartesian);
    var lat = Cesium.Math.toDegrees(cartographic.latitude);
    var lng = Cesium.Math.toDegrees(cartographic.longitude);
    var alt = cartographic.height;
    return { lng, lat, alt };
  },
 
  xgfx(baseHeigh) {
    if (this.RestrictTheHeight) {
      this.RestrictTheHeight.removeFromMap();
      this.RestrictTheHeight = null;
    }
    earthCtrl.factory.createSimpleGraphic(
      "polygon",
      { showSize: false },
      (entity) => {
        let arr = [];
        entity.polygon.hierarchy.getValue().positions.forEach((position) => {
          let cartographic =
            SmartEarth.Cesium.Cartographic.fromCartesian(position);
          let lat = SmartEarth.Cesium.Math.toDegrees(cartographic.latitude);
          let lng = SmartEarth.Cesium.Math.toDegrees(cartographic.longitude);
          arr.push(lng, lat);
        });
        this.earthCtrl.viewer.entities.remove(entity);
        if (viewer.terrainProvider) {
          Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, [
            Cesium.Cartographic.fromDegrees(arr[0], arr[1]),
          ]).then((updatedPositions) => {
            this.RestrictTheHeight = earthCtrl.analysis.createRestrictTheHeight(
              {
                positions: arr,
                baseHeight: baseHeigh + updatedPositions[0].height,
                // color: SmartEarth.Cesium.Color.GREEN.withAlpha(0.5),
                color:
                  SmartEarth.Cesium.Color.fromCssColorString(
                    "#ff1515"
                  ).withAlpha(0.5),
              }
            );
          });
        } else {
          this.RestrictTheHeight = earthCtrl.analysis.createRestrictTheHeight({
            positions: arr,
            baseHeight: baseHeigh,
            color:
              SmartEarth.Cesium.Color.fromCssColorString("#ff1515").withAlpha(
                0.5
              ),
          });
        }
      }
    );
  },
  hcqfxPoint(width) {
    const pointGraphic = earthCtrl.factory.createSimpleGraphic(
      "point",
      {},
      (entity) => {
        const position = entity.position.getValue();
        const { lng, lat } = this.transformCartesianToCoord(position);
        const pointBuffer = earthCtrl.analysis.createBufferAnalysis({
          position: [lng, lat],
          color: SmartEarth.Cesium.Color.YELLOW.withAlpha(0.5),
          radius: width / 1000,
        });
        pointBuffer.initBuffer();
        this.Buffers.push(pointBuffer);
      }
    );
  },
  hcqfxLine(width) {
    this.earthCtrl.factory.createSimpleGraphic(
      "polyline",
      { showSize: false },
      (entity) => {
        const positions = entity.polyline.positions.getValue();
        let coordinates = [];
        for (let i = 0; i < positions.length; i++) {
          const { lng, lat } = this.transformCartesianToCoord(positions[i]);
          coordinates.push(lng, lat);
        }
        const polulineBuffer = earthCtrl.analysis.createBufferAnalysis({
          position: coordinates,
          color: SmartEarth.Cesium.Color.YELLOW.withAlpha(0.5),
          radius: width / 1000,
        });
        polulineBuffer.initPolylineBuffer();
        this.Buffers.push(polulineBuffer);
      }
    );
  },
  hcqfxPolygon(width) {
    this.earthCtrl.factory.createSimpleGraphic(
      "polygon",
      { showSize: false },
      (entity) => {
        let positions = entity.polygon.hierarchy.getValue().positions;
        let coordinates = [];
        for (let i = 0; i < positions.length; i++) {
          const { lng, lat } = this.transformCartesianToCoord(positions[i]);
          coordinates.push(lng, lat);
        }
        const { lng, lat } = this.transformCartesianToCoord(positions[0]);
        coordinates.push(lng, lat);
        const polygonBuffer = earthCtrl.analysis.createBufferAnalysis({
          position: coordinates,
          color: SmartEarth.Cesium.Color.YELLOW.withAlpha(0.5),
          radius: width / 1000,
        });
        polygonBuffer.initPolylineBuffer();
        this.Buffers.push(polygonBuffer);
      }
    );
  },
  // 动态视域分析
  dtsyfxPoint(callback) {
    earthCtrl.factory.createSimpleGraphic("point", {}, (entity) => {
      let position = entity.position.getValue();
      let coord = this.transformCartesianToCoord(position);
      this.earthCtrl.viewer.entities.remove(entity);
      callback(coord);
    });
  },
  createViewShed(start, end, type) {
    let _lon = (end.lng - start.lng) / 100;
    let _lat = (end.lat - start.lat) / 100;
    this.clearViewShed();
    if (type == "normal") {
      this.movingViewShed = earthCtrl.analysis.createViewShed({
        isMouseCreate: false,
        ...{ lon: start.lng, lat: start.lat },
        heading: 90,
        distance: 100,
      });
      this.updateViewshed(start, _lon, _lat);
    } else {
      this.movingCircleViewshed = earthCtrl.analysis.createViewShedCircle({
        ...{ lon: start.lng, lat: start.lat },
        heading: 90,
        distance: 100,
        isSpherical: true,
      });
      this.updateCircleViewshed(start, _lon, _lat);
    }
  },
  updateViewshed(start, _lon, _lat) {
    clearInterval(this.time);
    let num = 1;
    this.time = setInterval(() => {
      num > 100 && (num = 0);
      this.movingViewShed &&
        this.movingViewShed.updateParameters({
          lon: start.lng + _lon * num,
          lat: start.lat + _lat * num,
          height: start.alt,
        });
      num++;
    }, 100);
  },
  updateCircleViewshed(start, _lon, _lat) {
    clearInterval(this.time);
    let num = 1;
    this.time = setInterval(() => {
      num > 100 && (num = 0);
      this.movingCircleViewshed &&
        this.movingCircleViewshed.update({
          lon: start.lng + _lon * num,
          lat: start.lat + _lat * num,
          height: start.alt,
        });
      num++;
    }, 100);
  },
  clearViewShed() {
    if (this.movingViewShed) {
      this.movingViewShed.removeFromMap();
      this.movingViewShed = null;
    }
    if (this.movingCircleViewshed) {
      this.movingCircleViewshed.close();
      this.movingCircleViewshed = null;
    }
  },
  // 阴影分析
  AnalysisSunshine() {
    if (!layerIsOpen) {
      layerIsOpen = true;
      let currentTime = viewer.clock.currentTime.clone();
      let startTime = viewer.clock.startTime.clone();
      let stopTime = viewer.clock.stopTime.clone();
      let multiplier = viewer.clock.multiplier;
      layer.open({
        type: 2,
        title: "阴影分析",
        shade: false,
        area: ["350px", "500px"],
        offset: "l",
        skin: "yyfxForm",
        content: SmartEarthRootUrl + "Workers/analysis/AnalysisSunshine.html",
        end: () => {
          window._AnalysisSunshine && window._AnalysisSunshine.remove();
          window._AnalysisSunshine = undefined;
          layerIsOpen = false;
        },
      });
    }
  },
  transformCartesianToCoord(position) {
    const cartographic = SmartEarth.Cesium.Cartographic.fromCartesian(position);
    const lat = SmartEarth.Cesium.Math.toDegrees(cartographic.latitude);
    const lng = SmartEarth.Cesium.Math.toDegrees(cartographic.longitude);
    const alt = cartographic.height;
    return { lng, lat, alt };
  },
  // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>图层管理<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  pointsArray: [],
  polygonArray: [],
  selectedEntity: null, //选中的实体
  addPointToMap(row) {
    const filteArr = this.pointsArray.filter((item) => item.type == row.type);
    if (filteArr.length > 0) {
      filteArr.forEach((item) => {
        item.entity.show = true;
      });
      return;
    }
    const that = this;
    row.list.forEach((item, index) => {
      let entity = this.earthCtrl.viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(item.lon, item.lat, 0),
        billboard: {
          // 图像地址,URI或Canvas的属性
          image: cameraIcon,
          // 大小是否以米为单位
          sizeInMeters: false,
          // 相对于坐标的垂直位置
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          // 相对于坐标的水平位置
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          // 应用于图像的统一比例。比例大于会1.0放大标签,而比例小于会1.0缩小标签。
          scale: 0.5,
          // 是否显示
          show: true,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
        //属性信息
        properties: {
          poiInfo: item,
        },
      });
      entity.click = function (callback) {
        that.handleEntityClick(this, callback);
      };
      const obj = {
        id: item.id,
        entity: entity,
        type: row.type,
      };
      that.pointsArray.push(obj);
    });
  },
  hidePointByType(row) {
    const filteArr = this.pointsArray.filter((item) => item.type == row.type);
    if (filteArr.length > 0) {
      filteArr.forEach((item) => {
        item.entity.show = false;
      });
    }
  },
  //entity点击事件
  handleEntityClick(entity, callback) {
    // 取消之前选中的Entity的高亮
    this.clearSelectedEntity();
    // 设置当前选中的Entity并高亮
    this.selectedEntity = entity;
    if (this.selectedEntity.billboard) {
      this.selectedEntity.billboard.image = cameraIconSel;
    }
    const poiInfo = entity.properties.poiInfo.getValue();
    callback(poiInfo);
  },
  setSelectedEntity(entity) {
    this.pointsArray.forEach((item) => {
      if (item.id === entity.id) {
        item.entity.billboard.image = cameraIconSel;
      }
    });
  },
  clearSelectedEntityStyle(entity) {
    this.pointsArray.forEach((item) => {
      if (item.id === entity.id) {
        item.entity.billboard.image = cameraIcon;
      }
    });
  },
  // 取消之前选中的Entity的高亮
  clearSelectedEntity() {
    if (this.selectedEntity && this.selectedEntity.billboard) {
      this.selectedEntity.billboard.image = cameraIcon;
      this.selectedEntity = null;
    }
  },
  createPolygonArea(item) {
    const findItem = this.polygonArray.find((row) => row.id === item.id);
    if (findItem) {
      earthCtrl.viewer.flyTo(findItem.polygon);
      return;
    }
    var curPolygon = earthCtrl.viewer.entities.add({
      name: "polygon",
      polygon: {
        hierarchy: Cesium.Cartesian3.fromDegreesArray(item.points),
        material: Cesium.Color.YELLOW.withAlpha(0.3),
        outline: true,
        outlineColor: Cesium.Color.RED.withAlpha(0.5),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      },
    });
    var polyPositions = curPolygon.polygon.hierarchy.getValue(
      Cesium.JulianDate.now()
    ).positions;
    var polyCenter = Cesium.BoundingSphere.fromPoints(polyPositions).center; //中心点
    polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
    curPolygon.position = polyCenter;
    curPolygon.label = {
      text: item.name,
      color: Cesium.Color.fromCssColorString("#fff"),
      font: "normal 32px MicroSoft YaHei",
      showBackground: true,
      scale: 0.5,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT_CLICK,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      disableDepthTestDistance: 10000.0,
    };
    const polyline = earthCtrl.viewer.entities.add({
      name: "boderLine",
      polyline: {
        positions: Cesium.Cartesian3.fromDegreesArray(item.points),
        width: 2,
        material: Cesium.Color.RED.withAlpha(0.5),
        clampToGround: true,
      },
    });
    earthCtrl.viewer.flyTo(curPolygon);
    const obj = {
      id: item.id,
      polygon: curPolygon,
      polyline: polyline,
    };
    this.polygonArray.push(obj);
  },
  clearPoygon() {
    this.polygonArray.forEach((item) => {
      earthCtrl.viewer.entities.remove(item.polygon);
      earthCtrl.viewer.entities.remove(item.polyline);
    });
    this.polygonArray = [];
  },
  // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>整体清除<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  toolClear() {
    var event = new MouseEvent("contextmenu", {
      view: window,
      bubbles: true,
      cancelable: false,
    });
    // 触发这个事件
    earthCtrl.viewer.canvas.dispatchEvent(event);
    earthCtrl.measure.clearResult();
    for (let i = 0; i < this.volumetricResults.length; i++) {
      let result = this.volumetricResults[i];
      if (result) {
        result.removeFromMap();
      }
    }
    this.volumetricResults = [];
    if (this.viewThrough) {
      this.viewThrough.deleteAll();
      this.viewThrough = null;
    }
    if (this.skyline) {
      this.skyline.removeFromMap();
      this.skyline = null;
    }
    if (this.viewShedTool) {
      this.viewShedTool.removeFromMap();
      this.viewShedTool = null;
    }
    if (this.RestrictTheHeight) {
      this.RestrictTheHeight.removeFromMap();
      this.RestrictTheHeight = null;
    }
    const graphic = earthCtrl.factory.SimpleGraphic;
    if (graphic) {
      graphic.clear();
    }
    this.Buffers.map((item) => {
      item.removeFromMap();
    });
    this.Buffers = [];
 
    this.timeShow = false;
 
    this.clearWgfx();
  },
  // 点位信息提取
  pick(open) {
    let tooltip = earthCtrl.core.createTooltip();
    tooltip.showFun(false);
    if (open) {
      ElMessage({
        message: "已开启拾取功能,再次点击则会关闭",
      });
      earthCtrl.pick((data, pickObject, movement) => {
        tooltip.showFun(false);
        console.log(data);
        let tooltipHTML = "";
        for (let key in data) {
          let value = data[key];
          value && (tooltipHTML += `${key}:${value || "无"}<br>`);
        }
        tooltip.showAts({ position: movement.position, text: tooltipHTML });
      });
    } else {
      ElMessage({
        message: "已关闭拾取功能",
      });
      tooltip.showFun(false);
      earthCtrl.endPick();
    }
  },
  // 水淹分析
  analysisFlood: null,
  addFlood() {
    const method = {
      pointSelect: true,
      spood: 50,
      GroupID: 0,
      url: SmartEarthRootUrl + "Workers/image/waterNormals.jpg",
    };
    this.analysisFlood = earthCtrl.analysis.createSubmergence(
      method,
      (value) => { }
    );
  },
  clearFlood() {
    this.analysisFlood && this.analysisFlood.endWater();
  },
  FloodAnalysis(type) {
    this.analysisFlood && this.analysisFlood.endWater();
    if (type === "close") {
      this.clearFlood();
    } else {
      ElMessage({
        message: "正在进行水淹分析,再次点击清除",
      });
      this.addFlood();
    }
  },
  // 等高线分析
  contourLabel: null,
  createContourLabel() {
    if (!this.contourLabel) {
      ElMessage({
        message: "等高线分析已开启,再次点击关闭",
      });
      this.contourLabel = earthCtrl.factory.createContourLabel();
    }
    this.contourLabel.showContourLabel(true);
  },
  closeContourLabel() {
    if (this.contourLabel) {
      this.contourLabel.showContourLabel(false);
    }
  },
};
 
export default mapUtils;