Cesium generates the coordinate information of the click point based on the mouse click

1. Demand

In daily development, you will encounter the situation that the coordinate information of the corresponding point is generated according to the mouse click

insert image description here

2. Analysis

1. Create a mouse click event

var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas); // 创建鼠标事件handler

handler.setInputAction(function(click) {
    
     // 监听鼠标左键点击事件
    var cartesian = viewer.camera.pickEllipsoid(click.position, viewer.scene.globe.ellipsoid); // 获取点击位置的地球坐标
    if (cartesian) {
    
    
        var entity = viewer.entities.add({
    
     // 在该位置添加点
            position: cartesian,
            point: {
    
    
                pixelSize: 10,
                color: Cesium.Color.YELLOW
            }
        });
        console.log('点的位置:', cartesian);
    }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
 

2. Click to generate coordinates but not latitude and longitude, but coordinates in the Cartesian coordinate system. At this time, a conversion is required

// 将 point 转换为单位向量
var length = Cesium.Cartesian3.magnitude(point);
var unitVector = Cesium.Cartesian3.divideByScalar(point, length, new Cesium.Cartesian3());

// 计算经纬度坐标
var cartographic = Cesium.Cartographic.fromCartesian(point);
var longitude = Cesium.Math.toDegrees(cartographic.longitude);
var latitude = Cesium.Math.toDegrees(cartographic.latitude);
var altitude = cartographic.height;

// 输出结果
console.log("经度:" + longitude);
console.log("纬度:" + latitude);
console.log("高度:" + altitude);
 

3. Complete code

var tempList = [];
// 创建鼠标事件handler
var handler = new Cesium.ScreenSpaceEventHandler(window.viewer.scene.canvas); 
handler.setInputAction(function(click) {
    
     // 监听鼠标左键点击事件
    // 获取点击位置的地球坐标
    var cartesian = window.viewer.camera.pickEllipsoid(click.position, window.viewer.scene.globe.ellipsoid);
    // 转换为笛卡尔坐标系 
    let cartographic1 = Cesium.Cartographic.fromCartesian(cartesian);
    // 转换为经纬度
    var latitude = Cesium.Math.toDegrees(cartographic1.latitude);
    var longitude = Cesium.Math.toDegrees(cartographic1.longitude);
    console.log(1001,longitude,latitude)
    tempList.push(longitude,latitude)
    // 控制点击生成两个点
    if ( tempList.length <=4) {
    
    
      if (cartesian) {
    
    
          var entity = window.viewer.entities.add({
    
     // 在该位置添加点
              position: cartesian,
              point: {
    
    
                  pixelSize: 10,
                  color: Cesium.Color.YELLOW
              }
          });
          
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

3. Data storage

因为在监听鼠标点击的时候是无法获取到 this 的,所以需要
const that=this

You can read this article for data storage and monitoring: data storage, click to jump

Guess you like

Origin blog.csdn.net/qq_53810245/article/details/132671937