首页 > 其他分享 >VUE - Cesium 测量

VUE - Cesium 测量

时间:2022-10-25 16:24:32浏览次数:75  
标签:VUE viewer positions 测量 var cartesian Cesium Math

VUE - Cesium 测量

 增加测量类:cesiumUtilMeasure.js

/** 测距 */
let CesiumUtilMeasure = {};

let handler = null;

let MEA = {
  Entitys: [],
};

//测量空间直线距离
/******************************************* */
CesiumUtilMeasure.measureLineSpace = () => {
  // 取消双击事件-追踪该位置
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

  handler = viewer.screenSpaceEventHandler;

  var positions = [];
  var poly = null;
  var distance = 0;
  var cartesian = null;
  var floatingPoint;

  handler.setInputAction(function (movement) {
    // tooltip.style.left = movement.endPosition.x + 3 + "px";
    // tooltip.style.top = movement.endPosition.y - 25 + "px";
    // tooltip.innerHTML = '<p>单击开始,右击结束</p>';
    // cartesian = viewer.scene.pickPosition(movement.endPosition);
    let ray = viewer.camera.getPickRay(movement.endPosition);
    cartesian = viewer.scene.globe.pick(ray, viewer.scene);
    //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
    if (positions.length >= 2) {
      if (!Cesium.defined(poly)) {
        poly = new PolyLinePrimitive(positions);
      } else {
        if (cartesian != null && cartesian.x != null) {
          positions.pop();
          // cartesian.y += (1 + Math.random());
          positions.push(cartesian);
        }
      }
      distance = getSpaceDistance(positions);
      // console.log("distance: " + distance);
      // tooltip.innerHTML='<p>'+distance+'米</p>';
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  handler.setInputAction(function (movement) {
    // tooltip.style.display = "none";
    // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
    // cartesian = viewer.scene.pickPosition(movement.position);
    let ray = viewer.camera.getPickRay(movement.position);
    cartesian = viewer.scene.globe.pick(ray, viewer.scene);

    if (cartesian != null && cartesian.x != null) {
      if (positions.length == 0) {
        positions.push(cartesian.clone());
      }
      positions.push(cartesian);
      //在三维场景中添加Label
      //   var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
      var textDisance = distance + '米';
      // console.log(textDisance + ",lng:" + cartographic.longitude/Math.PI*180.0);
      floatingPoint = viewer.entities.add({
        name: '直线距离',
        // position: Cesium.Cartesian3.fromDegrees(cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180,cartographic.height),
        position: positions[positions.length - 1],
        point: {
          pixelSize: 5,
          color: Cesium.Color.RED,
          outlineColor: Cesium.Color.WHITE,
          outlineWidth: 2,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
        },
        label: {
          text: textDisance,
          font: '18px sans-serif',
          fillColor: Cesium.Color.GOLD,
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(20, -20),
        },
      });

      MEA.Entitys.push(floatingPoint);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  handler.setInputAction(function (movement) {
    let linetemp = MEA.Entitys.filter((t) => t._name == '直线')[0];
    let pois = linetemp.polyline.positions.getValue();
    pois.pop();
    linetemp.polyline.positions = pois;

    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  // }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

  // handler.setInputAction(function (movement) {
  //   // handler.destroy(); //关闭事件句柄
  //   // positions.pop(); //最后一个点无效
  //   stopHandler();
  //   // viewer.entities.remove(floatingPoint);
  //   // tooltip.style.display = "none";
  // }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  var PolyLinePrimitive = (function () {
    function _(positions) {
      this.options = {
        name: '直线',
        polyline: {
          show: true,
          positions: [],
          material: Cesium.Color.CHARTREUSE,
          width: 3,
          clampToGround: true,
        },
      };
      this.positions = positions;
      this._init();
    }

    _.prototype._init = function () {
      var _self = this;
      var _update = function () {
        return _self.positions;
      };
      //实时更新polyline.positions
      this.options.polyline.positions = new Cesium.CallbackProperty(_update, false);

      let lineTemp = viewer.entities.add(this.options);

      MEA.Entitys.push(lineTemp);
    };

    return _;
  })();

  //空间两点距离计算函数
  function getSpaceDistance(positions) {
    var distance = 0;
    for (var i = 0; i < positions.length - 1; i++) {
      var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
      var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
      /**根据经纬度计算出距离**/
      var geodesic = new Cesium.EllipsoidGeodesic();
      geodesic.setEndPoints(point1cartographic, point2cartographic);
      var s = geodesic.surfaceDistance;
      //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
      //返回两点之间的距离
      s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
      distance = distance + s;
    }
    return distance.toFixed(2);
  }
};

function stopHandler() {
  if (handler != null) {
    handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  }
  debugger;
  if (viewer != null) {
    MEA.Entitys.forEach((e) => {
      viewer.entities.remove(e);
    });
  }

  MEA.Entitys = [];
}

CesiumUtilMeasure.stopHandler = () => {
  stopHandler();
};

export default CesiumUtilMeasure;

//****************************测量空间面积************************************************//
// export function measureAreaSpace(viewer) {
//   // 取消双击事件-追踪该位置
//   viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
//   // 鼠标事件
//   // let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene._imageryLayerCollection);
//   var handler = viewer.screenSpaceEventHandler;

//   var positions = [];
//   var tempPoints = [];
//   var polygon = null;
//   // var tooltip = document.getElementById("toolTip");
//   var cartesian = null;
//   var floatingPoint;//浮动点
//   // tooltip.style.display = "block";

//   handler.setInputAction(function (movement) {
//     // tooltip.style.left = movement.endPosition.x + 3 + "px";
//     // tooltip.style.top = movement.endPosition.y - 25 + "px";
//     // tooltip.innerHTML ='<p>单击开始,右击结束</p>';
//     // cartesian = viewer.scene.pickPosition(movement.endPosition);
//     let ray = viewer.camera.getPickRay(movement.endPosition);
//     cartesian = viewer.scene.globe.pick(ray, viewer.scene);
//     //cartesian = viewer.scene.camera.pickEllipsoid(movement.endPosition, viewer.scene.globe.ellipsoid);
//     if (positions.length >= 2) {
//       if (!Cesium.defined(polygon)) {
//         polygon = new PolygonPrimitive(positions);
//       } else {
//         positions.pop();
//         // cartesian.y += (1 + Math.random());
//         positions.push(cartesian);
//       }
//       // tooltip.innerHTML='<p>'+distance+'米</p>';
//     }
//   }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

//   handler.setInputAction(function (movement) {
//     // tooltip.style.display = "none";
//     // cartesian = viewer.scene.pickPosition(movement.position);
//     let ray = viewer.camera.getPickRay(movement.position);
//     cartesian = viewer.scene.globe.pick(ray, viewer.scene);
//     // cartesian = viewer.scene.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
//     if (positions.length == 0) {
//       positions.push(cartesian.clone());
//     }
//     //positions.pop();
//     positions.push(cartesian);
//     //在三维场景中添加点
//     var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
//     var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
//     var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
//     var heightString = cartographic.height;
//     tempPoints.push({ lon: longitudeString, lat: latitudeString, hei: heightString });
//     floatingPoint = viewer.entities.add({
//       name: '多边形面积',
//       position: positions[positions.length - 1],
//       point: {
//         pixelSize: 5,
//         color: Cesium.Color.RED,
//         outlineColor: Cesium.Color.WHITE,
//         outlineWidth: 2,
//         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
//       }
//     });
//   }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

//   handler.setInputAction(function (movement) {
//     handler.destroy();
//     positions.pop();
//     //tempPoints.pop();
//     // viewer.entities.remove(floatingPoint);
//     // tooltip.style.display = "none";
//     //在三维场景中添加点
//     // var cartographic = Cesium.Cartographic.fromCartesian(positions[positions.length - 1]);
//     // var longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
//     // var latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
//     // var heightString = cartographic.height;
//     // tempPoints.push({ lon: longitudeString, lat: latitudeString ,hei:heightString});

//     var textArea = getArea(tempPoints) + "平方公里";
//     viewer.entities.add({
//       name: '多边形面积',
//       position: positions[positions.length - 1],
//       // point : {
//       //  pixelSize : 5,
//       //  color : Cesium.Color.RED,
//       //  outlineColor : Cesium.Color.WHITE,
//       //  outlineWidth : 2,
//       //  heightReference:Cesium.HeightReference.CLAMP_TO_GROUND
//       // },
//       label: {
//         text: textArea,
//         font: '18px sans-serif',
//         fillColor: Cesium.Color.GOLD,
//         style: Cesium.LabelStyle.FILL_AND_OUTLINE,
//         outlineWidth: 2,
//         verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
//         pixelOffset: new Cesium.Cartesian2(20, -40),
//         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
//       }
//     });
//   }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

//   var radiansPerDegree = Math.PI / 180.0;//角度转化为弧度(rad)
//   var degreesPerRadian = 180.0 / Math.PI;//弧度转化为角度

//   //计算多边形面积
//   function getArea(points) {

//     var res = 0;
//     //拆分三角曲面

//     for (var i = 0; i < points.length - 2; i++) {
//       var j = (i + 1) % points.length;
//       var k = (i + 2) % points.length;
//       var totalAngle = Angle(points[i], points[j], points[k]);

//       var dis_temp1 = distance(positions[i], positions[j]);
//       var dis_temp2 = distance(positions[j], positions[k]);
//       res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
//       console.log(res);
//     }

//     return (res / 1000000.0).toFixed(4);
//   }

//   /*角度*/
//   function Angle(p1, p2, p3) {
//     var bearing21 = Bearing(p2, p1);
//     var bearing23 = Bearing(p2, p3);
//     var angle = bearing21 - bearing23;
//     if (angle < 0) {
//       angle += 360;
//     }
//     return angle;
//   }
//   /*方向*/
//   function Bearing(from, to) {
//     var lat1 = from.lat * radiansPerDegree;
//     var lon1 = from.lon * radiansPerDegree;
//     var lat2 = to.lat * radiansPerDegree;
//     var lon2 = to.lon * radiansPerDegree;
//     var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
//     if (angle < 0) {
//       angle += Math.PI * 2.0;
//     }
//     angle = angle * degreesPerRadian;//角度
//     return angle;
//   }

//   var PolygonPrimitive = (function () {
//     function _(positions) {
//       this.options = {
//         name: '多边形',
//         polygon: {
//           hierarchy: [],
//           // perPositionHeight : true,
//           material: Cesium.Color.GREEN.withAlpha(0.5),
//           // heightReference:20000
//         }
//       };

//       this.hierarchy = { positions };
//       this._init();
//     }

//     _.prototype._init = function () {
//       var _self = this;
//       var _update = function () {
//         return _self.hierarchy;
//       };
//       //实时更新polygon.hierarchy
//       this.options.polygon.hierarchy = new Cesium.CallbackProperty(_update, false);
//       viewer.entities.add(this.options);
//     };

//     return _;
//   })();

//   function distance(point1, point2) {
//     var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
//     var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
//     /**根据经纬度计算出距离**/
//     var geodesic = new Cesium.EllipsoidGeodesic();
//     geodesic.setEndPoints(point1cartographic, point2cartographic);
//     var s = geodesic.surfaceDistance;
//     //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
//     //返回两点之间的距离
//     s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic.height, 2));
//     return s;
//   }

// }

 

 

vue 文件中引入:

<template>   <div class="cc-tool">      <a-tooltip placement="bottom">
        <template slot="title">
          <span>测量</span>
        </template>
        <div class="svgbox" @click="toggleMeasure">
          <measure-svg :color="isMeasure ? 'orange' : 'grey'" alt="light" />
        </div>
      </a-tooltip>
  </div> </template>

 

<script>import MchangeSvg from '@/assets/icons/mchange.svg?inline';
import CesiumUtilMeasure from './utils/cesiumUtilMeasure';
 
export default {
  components: {MeasureSvg },
  data() {
    return {
      isMeasure: false
    };
  },
  methods: {//测量
    toggleMeasure() {
      this.isMeasure ? CesiumUtilMeasure.stopHandler() : CesiumUtilMeasure.measureLineSpace();
      this.isMeasure = !this.isMeasure;
    },
  },
};
</script>

 

 

 

标签:VUE,viewer,positions,测量,var,cartesian,Cesium,Math
From: https://www.cnblogs.com/1285026182YUAN/p/16825249.html

相关文章

  • Vuex3的状态管理
    一.Vuex是什么Vue全局事件总线Vuex状态管理何时使用Vuex二.纯vue组件案例计算总数案例添加人员案例三.Vuex工作原理和流程第一种工作流程第二种工作流程生活化的Vuex工......
  • Vue要做权限管理该怎么做?控制到按钮级别的权限怎么做
    一、是什么权限是对特定资源的访问许可,所谓权限控制,也就是确保用户只能访问到被分配的资源而前端权限归根结底是请求的发起权,请求的发起可能有下面两种形式触发页面加......
  • vue路由导航守卫
    简单来说路由导航守卫就是.可以让我们对用户要跳转的路由做一次检查,符合条件的就放行,不符合条件则强制用户跳转至登录页面,说白了就时路由导航守卫是为了路由跳转之前做的......
  • vue开发整理
    1.先检查项目是否有,接下来输入命令行:npminstall加载依赖包node_modulesnpminstall//下载依赖包命令2.如果安装失败请删除node_modulese文件夹,并清除缓存npm......
  • 01_初识Vue
    1.基础代码<!--html代码--><divid="root"><h1>hello,{{name.toUpperCase()}},{{address}}!</h1></div><!--js代码--><script>Vue.config.produ......
  • 网友心得—运行jeecgboot-vue3项目可能出现的问题
    运行jeecgboot-vue3项目可能出现的问题1.执行pnpminstall的时候报错ERR_PNPM_INVALID_OVERRIDE_SELECTOR Cannotparsethe"//"selectorintheoverrides​ 翻......
  • Vue之条件,列表渲染和事件处理的使用
    style和class<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Title</title><scriptsrc="./js/vue.js"></script><style......
  • Vue常见面试题
    Vue常见面试题1、Vue的优点2、说说你对SPA单页面的理解,它的优缺点分别是什么?3、SPA首屏加载速度慢的怎么解决?4、Vue初始化过程中(newVue(options))都做了什么?5、对MVVM的理......
  • vue3 + ts 中出现 类型“typeof import(".........../node_modules/vue/dist/vue")”
    错误示例截图解决方法修改shims-vue.d.ts中的内容declaremodule"*.vue"{ import{defineComponent}from"vue"; constComponent:ReturnType<typeofdefineC......
  • vue项目中使用axios获取本地json文件,报404错(已解决✔)
    vue项目中VueX的组件store里面有个actions的axiosget请求,请求本地的JSON文件的时候就报错404了。看了好久资料最终解决了。虽然刚开始的时候我已近把静态资源放在了pub......