套件能力演示

三维标绘、量算、位置拾取、拖拽与模型位置调整。下面是该示例的核心 script 片段,供参考学习;完整可运行代码请进入在线 Demo 或查看仓库源码。

在线运行 Demo 全部示例 查看完整源码

示例代码

import * as Cesium from 'cesium'
import { initCesium } from '@/utils/cesiumPluginsExtends/index'
import { AnnotationStore, AnnotationLayer } from '@/utils/cesiumPluginsExtends/annotation/index'
import { PlotStore, PlotLayer } from '@/utils/cesiumPluginsExtends/plot/index'
import {
  defineDrawToolbar,
  bindDrawToolbar
} from '@/utils/cesiumPluginsExtends/web-components/index'

// 演示区域中心(成都附近)
const CENTER = [104.09, 30.65]

export default {
  data () {
    return {
      annoState: { size: 0, canUndo: false, canRedo: false },
      plotState: { size: 0, canUndo: false, canRedo: false },
      profileStats: null,
      jsonPreview: ''
    }
  },
  mounted () {
    this.initMap()
  },
  beforeUnmount () {
    if (this.unbindToolbar) this.unbindToolbar()
    if (this.annoLayer) this.annoLayer.destroy()
    if (this.plotLayer) this.plotLayer.destroy()
    this.c_viewer = null
  },
  methods: {
    async addWorldTerrain (viewer) {
      try {
        const provider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1)
        viewer.terrainProvider = provider
      } catch (error) {
        console.log(`Failed to add world terrain: ${error}`)
      }
    },
    initMap () {
      Cesium.Ion.defaultAccessToken = import.meta.env.VITE_CESIUM_ION_TOKEN
      const { viewer, analysis } = new initCesium({
        cesiumGlobal: Cesium,
        containerId: 'cesiumContainer',
        viewerConfig: { infoBox: false, shouldAnimate: true },
        extraConfig: {
          depthTest: true,
          AccessToken: import.meta.env.VITE_CESIUM_ION_TOKEN
        },
        MapImageryList: [
          {
            type: 'UrlTemplateImageryProvider',
            option: {
              url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
              subdomains: ['0', '1', '2', '3'],
              tilingScheme: new Cesium.WebMercatorTilingScheme()
            }
          }
        ]
      })
      this.c_viewer = viewer
      this.analysis = analysis
      this.addWorldTerrain(viewer)

      // ① 标注:数据层 + Cesium 绑定层
      this.annoStore = new AnnotationStore()
      this.annoLayer = new AnnotationLayer({ Cesium, viewer, store: this.annoStore })
      this.annoStore.subscribe((snapshot) => {
        this.annoState = {
          size: snapshot.annotations.length,
          canUndo: snapshot.canUndo,
          canRedo: snapshot.canRedo
        }
      })

      // ② 标绘:数据层 + Cesium 绑定层
      this.plotStore = new PlotStore()
      this.plotLayer = new PlotLayer({ Cesium, viewer, store: this.plotStore })
      this.plotStore.subscribe((snapshot) => {
        this.plotState = {
          size: snapshot.plots.length,
          canUndo: snapshot.canUndo,
          canRedo: snapshot.canRedo
        }
      })

      // ① 的 Web Components 工具条
      defineDrawToolbar()
      const toolbar = document.createElement('cesium-draw-toolbar')
      toolbar.setAttribute('modes', 'point,polyline,polygon')
      this.$refs.toolbarHost.appendChild(toolbar)
      this.unbindToolbar = bindDrawToolbar(toolbar, {
        point: () => this.addAnnotation('point'),
        polyline: () => this.addAnnotation('polyline'),
        polygon: () => this.addAnnotation('polygon'),
        cancel: () => {
          toolbar.value = null
        }
      })

      this.flyTo()
    },
    flyTo () {
      this.c_viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(CENTER[0], CENTER[1], 12000),
        orientation: { heading: 0, pitch: Cesium.Math.toRadians(-55), roll: 0 }
      })
    },
    jitter (range = 0.012) {
      return (Math.random() - 0.5) * range
    },
    randomPoint () {
      return [CENTER[0] + this.jitter(), CENTER[1] + this.jitter()]
    },

    /* ---------------- ① 标注 ---------------- */
    addAnnotation (type) {
      const p1 = this.randomPoint()
      if (type === 'point') {
        this.annoStore.add({ type: 'point', positions: [p1], style: { color: '#ffcc00', pointSize: 10 } })
        return
      }
      const p2 = this.randomPoint()
      if (type === 'polyline') {
        this.annoStore.add({ type: 'polyline', positions: [p1, p2], style: { color: '#4fc3f7', lineWidth: 3 } })
        return
      }
      this.annoStore.add({
        type: 'polygon',
        positions: [p1, p2, this.randomPoint()],
        style: { color: '#66bb6a', clampToGround: true }
      })
    },
    annoUndo () { this.annoStore.undo() },
    annoRedo () { this.annoStore.redo() },
    annoClear () { this.annoStore.clear() },
    annoExport () {
      this.jsonPreview = JSON.stringify(this.annoStore.toJSON(), null, 2)
    },
    annoLoad () {
      if (!this.jsonPreview) { this.annoExport(); return }
      try { this.annoStore.load(JSON.parse(this.jsonPreview)) } catch (error) { console.warn(error) }
    },

    /* ---------------- ② 标绘 ---------------- */
    addPlot (type) {
      const points = []
      const n = type === 'StraightArrow' ? 3 : 4
      for (let i = 0; i < n; i++) points.push(this.randomPoint())
      this.plotStore.add({ type, positions: points, fillMaterial: '#ff5252' })
    },
    plotUndo () { this.plotStore.undo() },
    plotRedo () { this.plotStore.redo() },
    plotClear () { this.plotStore.clear() },
    plotExport () {
      this.jsonPreview = JSON.stringify(this.plotStore.toJSON(), null, 2)
    },
    plotLoad () {
      if (!this.jsonPreview) { this.plotExport(); return }
      try { this.plotStore.load(JSON.parse(this.jsonPreview)) } catch (error) { console.warn(error) }
    },

    /* ---------------- ③ 剖面分析 ---------------- */
    profileInteractive () {
      this.analysis.createProfileAnalysis({
        chart: true,
        callback: (result) => {
          this.profileStats = result.stats
        }
      })
    },
    profileFixed () {
      this.analysis.createProfileAnalysis({
        positions: [
          [CENTER[0] - 0.01, CENTER[1] - 0.01],
          [CENTER[0] + 0.01, CENTER[1] + 0.01]
        ],
        samples: 200,
        chart: true,
        callback: (result) => {
          this.profileStats = result.stats
        }
      })
    }
  }
}

相关 API

安装:npm install cesium_dev_kit cesium