【超图+CESIUM】【基础API使用示例】42、超图|CESIUM - 绘制编辑线段|读取kml文件绘制编辑|导出kml线段数据

前言

	缺少前置学习使用资料,请自行查阅:[https://blog.csdn.net/weixin_44402694/article/details/123110136](https://blog.csdn.net/weixin_44402694/article/details/123110136)
	以下示例使用到的公共静态资料,不建议下载,建议官网自行下载超图Build资源,示例所涉及图片会在示例使用到时提供出来。如有需要可下载:[https://download.csdn.net/download/weixin_44402694/82180350](https://download.csdn.net/download/weixin_44402694/82180350)。
	绘制编辑线段|读取kml文件绘制编辑|导出kml线段数据。

使用

  • 效果
    【超图+CESIUM】【基础API使用示例】42、超图|CESIUM - 绘制编辑线段|读取kml文件绘制编辑|导出kml线段数据_第1张图片

  • 完整代码


<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>线 - 绘制编辑保存title>
    <link href="./public/Build/Cesium/Widgets/widgets.css" rel="stylesheet" />
    <script
      type="text/javascript"
      src="./public/Build/Cesium/Cesium.js"
    >script>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body,
      #cesium-container {
        width: 100%;
        height: 100%;
      }
      .panel {
        position: fixed;
        left: 10px;
        top: 10px;
        z-index: 1;
        background-color: #fff;
        padding: 10px;
      }
      .panel .btn {
        cursor: pointer;
      }
      .panel .check {
        cursor: pointer;
      }
      .tooltip {
        position: fixed;
        left: 0;
        top: 0;
        background: rgba(0, 0, 0, 0.4);
        padding: 4px;
        border-radius: 4px;
        display: none;
        z-index: 1;
        color: #fff;
      }
    style>
  head>
  <body>
    <div id="cesium-container" />
    <div class="panel">
      <p class="btn">绘制并编辑线p>
      <p class="btn">保存KML文件p>
      <p class="btn">打开KML文件p>
      <p class="btn">清空p>
      <p class="check">是否编辑Z值 <input type="checkbox" />p>
    div>
    <div class="tooltip">div>
    <input type="file" accept=".kml" class="file" style="display: none;">
    <script>
      let viewer, scene, editHandler
      window.onload = function () {
        viewer = new Cesium.Viewer('cesium-container', {
          sceneModePicker: true,
          navigation: false,
          selectionIndicator: false, // 聚焦失效
        })
        scene = viewer.scene
        setS3MServiceHandler()
        initBindDrawEventHandler()
      }

      // 初始化绑定按钮的绘制事件
      function initBindDrawEventHandler() {
        const btns = document.querySelectorAll('.panel .btn')
        btns[0].addEventListener('click', () => {
          drawLine(handleEdit)
        })
        btns[1].addEventListener('click', () => {
          handleSaveClick()
        })
        btns[2].addEventListener('click', () => {
          handleOpenClick()
        })
        btns[3].addEventListener('click', () => {
          if (editHandler) {
            editHandler.clear()
            editHandler.deactivate()
          }
          viewer.entities.removeAll()
          let dataSources = viewer.dataSources
          dataSources.removeAll()
        })

        const check = document.querySelector('.check input')
        check.addEventListener('click', () => {
          editHandler && (editHandler.isEditZ = check.checked)
        })
      }
      // 画线
      function drawLine(callback) {
        const positions = []
        let poly, entity, drawingEntity
        let isDrawing = true
        let handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
        let polyLineEntity = (function () {
          function _(positions) {
            // polyline 配置
            this.options = {
              name: 'polyline',
              polyline: {
                show: true,
                positions: [],
                material: Cesium.Color.GREEN,
                width: 3,
              },
            }
            this.positions = positions
            this._init()
          }

          _.prototype._init = function () {
            let _self = this
            this.options.polyline.positions = new Cesium.CallbackProperty(
              function () {
                return _self.positions
              },
              false
            )
            drawingEntity = entity = viewer.entities.add(this.options)
          }
          return _
        })()
        handler.setInputAction(function (movement) {
          let ent = viewer.selectedEntity
          // 当前选中的entity不是绘制的entity,就return。实现绘制时也能选择
          if (ent && drawingEntity !== ent) {
            return
          }
          isDrawing = true
          let cartesian = viewer.scene.pickPosition(movement.position)
          if (positions.length == 0) {
            positions.push(cartesian.clone())
          }
          positions.push(cartesian)
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler.setInputAction((movement) => {
          let cartesian = viewer.scene.pickPosition(movement.endPosition)
          if (positions.length >= 2) {
            if (!Cesium.defined(poly)) {
              poly = new polyLineEntity(positions)
            } else {
              if (cartesian != undefined) {
                positions.pop()
                positions.push(cartesian)
              }
            }
          }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        handler.setInputAction((movement) => {
          positions.pop()
          isDrawing = false
          handler = handler && handler.destroy() // clear and empty the handler.
          callback && callback(entity)
          // 继续绘制
          // this.drawLine(this.handleEdit);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      }
      // 编辑
      function handleEdit(entity) {
        if (!entity) {
          editHandler && editHandler.deactivate()
          return
        }
        if (!editHandler) {
          editHandler = new Cesium.EditHandler(viewer, entity)
          const check = document.querySelector('.check input')
          editHandler.isEditZ = check.checked // 是否开启编辑Z值
          editHandler.activate()
        } else {
          editHandler.deactivate()
          editHandler.setEditObject(entity)
          editHandler.activate()
        }
      }
      // 下载文件
      function handleSaveClick() {
        let funDownload = function (content, filename) {
          let eleLink = document.createElement('a')
          eleLink.download = filename
          eleLink.style.display = 'none'
          // 字符内容转变成blob地址
          let blob = new Blob([content])
          eleLink.href = URL.createObjectURL(blob)
          // 触发点击
          document.body.appendChild(eleLink)
          eleLink.click()
          // 然后移除
          document.body.removeChild(eleLink)
        }
        let entities = new Cesium.EntityCollection()
        let dataSources = viewer.dataSources
        for (let i = 0, j = dataSources.length; i < j; i++) {
          for (let v of dataSources.get(i).entities.values) {
            entities.add(v)
          }
        }
        for (let v of viewer.entities.values) {
          entities.add(v)
        }

        if (entities.values.length) {
          let promise = Cesium.exportKml({ entities: entities })
          promise.then(function (e) {
            funDownload(e.kml, new Date().getTime() + '.kml')
          })
        } else {
          alert('当前场景没有entities实体')
        }
      }
      // 打开文件
      function handleOpenClick() {
        let fileInput = document.querySelector('.file')

        fileInput.onchange = function (evt) {
          let files = evt.target.files
          if (files.length > 0) {
            let file = evt.target.files[0]
            let fileReader = new FileReader()
            // console.log(file)
            fileReader.onload = function () {
              viewer.dataSources
                .add(
                  Cesium.KmlDataSource.load(new Blob([this.result]), {
                    camera: viewer.scene.camera,
                    canvas: viewer.scene.canvas,
                  })
                )
                .then(function (kmlDataSource) {
                  let entities = kmlDataSource.entities
                  let item = entities.values[entities.values.length - 1]
                  self.handleEdit(item)
                  viewer.zoomTo(entities)
                })
              fileInput = null
              fileReader = null
            }
            fileReader.readAsText(file)
          }
          fileInput.value = null
        }
        fileInput.click()
      }

      // 添加由supermap iserver上发布的s3m服务
      function setS3MServiceHandler() {
        const promise = viewer.scene.open(
          'http://www.supermapol.com/realspace/services/3D-NewCBD/rest/realspace'
        )
        Cesium.when(promise, (layers) => {
          layers.forEach((l) => {
            l.selectEnabled = false // 不允许模型被选中
          })
        })
      }
    script>
  body>
html>

你可能感兴趣的:(超图+CESIUMJS,超图+CESIUM)