Cesium 实现距离测算

假装没事ソ 提交于 2020-03-06 17:43:05
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Use correct character set. -->
  <meta charset="utf-8">
  <!-- Tell IE to use the latest, best version. -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <meta name="description" content="A simple CZML example showing four satellites in orbit around the Earth, and some ground objects.">
  <meta name="cesium-sandcastle-labels" content="Showcases, DataSources">
  <title>距离测算!</title>
  <script src="../Build/Cesium/Cesium.js"></script>
  <!-- <script type="text/javascript" src="Sandcastle/Sandcastle-header.js"></script> -->
  <script type="text/javascript" src="../Build/CesiumUnminified/Cesium.js" nomodule></script>
  <script type="module" src="Sandcastle/load-cesium-es6.js"></script>
  <script type="text/javascript" src="/emc/js/jquery-easyui-1.5.2/jquery.min.js"></script>
  <style>
      @import url(../Build/Cesium/Widgets/widgets.css);
      html, body, #cesiumContainer {
          width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
      }
  </style>
</head>
<body>
  <div id="cesiumContainer"></div>
     <button type="button" class="btn btn-info"  style="position:absolute;top:20px;left: 95px;" οnclick="SetMode()">测量</button>
     <button type="button" class="btn btn-info"  style="position:absolute;top:20px;left: 185px;" οnclick="clearDrawingBoard()">清除</button>
 
  <div  id="toolTip" style="display:none;position:absolute;height:20px;width:127px;background: olive;top:0px;left:0px">
   </div>
  <script>
   
   var viewer = new Cesium.Viewer("cesiumContainer", {
				   imageryProvider: new Cesium.UrlTemplateImageryProvider({
					   url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
			       })

	           });
   
   //设置相机位置、视角
   viewer.scene.camera.setView({
       destination : new Cesium.Cartesian3(-1206939.1925299785, 5337998.241228442, 3286279.2424502545),
       orientation : {
           heading : 1.4059101895600987,
           pitch : -0.20917672793046682,
           roll : 2.708944180085382e-13
       }
   }); 
   
   var handler;
   var tempEntities = [];
   
   function SetMode(){
	  
	   
	   measureLineSpace(viewer);
   }
   
   function measureLineSpace(viewer) {
	   
	       handler=new Cesium.ScreenSpaceEventHandler(viewer.scene._imageryLayerCollection);
	   
           var positions = [];
           var poly = null;
           var tooltip = document.getElementById("toolTip");
           var distance = 0;
           var cartesian = null;
           var floatingPoint;
           tooltip.style.display = "block";
           //监听移动事件
           handler.setInputAction(function (movement) {
               tooltip.style.left = movement.endPosition.x +440+ "px";
               tooltip.style.top = movement.endPosition.y+30+ "px";
               tooltip.innerHTML = '<p>单击开始,双击结束</p>';
               //移动结束位置
               cartesian = viewer.scene.pickPosition(movement.endPosition);   
               //判断点是否在画布上
               if(Cesium.defined(cartesian)){
                   if (positions.length >= 2) {
                       if (!Cesium.defined(poly)) {
                           //画线
                           poly = new PolyLinePrimitive(positions);
                           
                       } else {
                           positions.pop();
                           positions.push(cartesian);
                       }
                       distance = getSpaceDistance(positions);
                   }
               }

           }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
           //监听单击事件
           handler.setInputAction(function (movement) {
               tooltip.style.display = "none";
               cartesian = viewer.scene.pickPosition(movement.position); 
            
               if(Cesium.defined(cartesian)){
               if (positions.length == 0) {
                   positions.push(cartesian.clone());
               }
               positions.push(cartesian);
               //在三维场景中添加Label
               var textDisance = distance > 1000 ? (distance/1000).toFixed(2) + 'km' : distance.toFixed(2) + 'm';;
               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.NONE
                   },
                   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),
                       heightReference:Cesium.HeightReference.NONE
                   }
               });
               

               tempEntities.push(floatingPoint);
           }
    
           }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
           //监听双击事件
           handler.setInputAction(function (movement) {
               positions.pop();//最后一个点无效
               handler.destroy();//关闭事件句柄
           }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
           }
//绘线效果1         
   var PolyLinePrimitive = (function () {
       function _(positions) {
           this.options = {
               name: '直线',
               polyline: {
                   show: true,
                   positions: [],
                   material: Cesium.Color.CHARTREUSE  ,
                   width: 2            
               }
           };
           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);
           var line =  viewer.entities.add(this.options);
           
           tempEntities.push(line);
           
       };

       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 clearDrawingBoard() {
       var primitives = viewer.entities;
           for (i = 0; i <  tempEntities.length; i++) {
               primitives.remove(tempEntities[i]);
       }
       
       tempEntities = [];
   }

	
  </script>
</body>
</html>

效果如下:

小古

 

参考博客:

https://www.jianshu.com/p/4a97d3ed4a06

https://blog.csdn.net/wt346326775/article/details/83721060

另感谢两位博主的博客;

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!