软键盘控制cesium相机移动旋转

1.有航向 类似于控制飞机飞行

html 复制代码
<!DOCTYPE html>
<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">
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.80/Build/Cesium/Cesium.js"></script>
    <link rel="stylesheet"
        href="https://cesium.com/downloads/cesiumjs/releases/1.80/Build/Cesium/Widgets/widgets.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/Turf.js/6.5.0/turf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@dvgis/cesium-map/dist/cesium.map.min.js"></script>
    <title>Document</title>
    <style>
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        #cesiumContainer {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        .lonLat {
            position: fixed;
            width: 100%;
            bottom: 0;
            /* left: 50%; */
            color: aliceblue;
            text-align: center;
        }

        button:focus {
            outline: none;
            /* 取消选中时的轮廓边框 */
            box-shadow: none;
            /* 取消选中时的阴影效果 */

        }

        button {
            width: 80px;
            height: 50px;
            -webkit-user-select: none;
            /* Chrome, Safari, Opera */
            -moz-user-select: none;
            /* Firefox */
            -ms-user-select: none;
            /* Internet Explorer/Edge */
            user-select: none;
            /* 此规则适用于大多数浏览器 */
        }
    </style>
</head>

<body>
    <div id="cesiumContainer"></div>
    <div class="lonLat">
        <button class="btn1">前</button>
        <button class="btn2">后</button>
        <button class="btn3">左</button>
        <button class="btn4">右</button>
        <button class="btn5">上</button>
        <button class="btn6">下</button>
        <button class="rotation1">旋转heading+</button>
        <button class="rotation2">旋转heading-</button>
        <button class="rotation5">旋转pitch+</button>
        <button class="rotation6">旋转pitch-</button>
        <button class="rotation3">旋转roll+</button>
        <button class="rotation4">旋转roll-</button>
        <button class="openC">开启</button>
        <button class="closeC">关闭</button>
    </div>
    <script>
        // document.oncontextmenu = new Function("event.returnValue=false");
        // document.onselectstart = new Function("event.returnValue=false");
        // document.addEventListener("keydown", function (e) {
        //  		console.log(e.key);
        //         if (e.key == "F12") {
        //           e.preventDefault(); // 如果按下键F12,阻止事件
        //         }
        //     });



        var viewerWindow = new Cesium.Viewer("cesiumContainer", {


            geocoder: false, // 位置查找工具
            timeline: false, // 底部时间线
            homeButton: false, // 视角返回初始位置
            fullscreenButton: false, // 全屏
            animation: false, // 左下角仪表盘(动画器件)
            sceneModePicker: false, // 选择视角的模式(球体、平铺、斜视平铺)
            navigationHelpButton: false, //导航帮助按钮
            targetFrameRate: 30,
            imageryProvider: new Cesium.SingleTileImageryProvider({
                url: "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=",
            }),
            baseLayerPicker: false,
        });

        // 不显示底图
        // viewerWindow.imageryLayers.get(0).show = false;
        // 去除logo
        viewerWindow.cesiumWidget.creditContainer.style.display = "none";

        // 高德
        var optionsG = {
            style: 'img', // style: img、elec、cva//地标 网路
            crs: 'WGS84', // 使用84坐标系,默认为:GCJ02
            maximumLevel: 18, // 设置最大级别
            // minimumLevel: 5   // 设置最小级别
        }
        viewerWindow.imageryLayers.add(new Cesium.ImageryLayer(new AmapImageryProvider(optionsG)))
        // // 腾讯
        // var optionsT = {
        //     style: 'img' //style: img、1:经典
        // }
        // viewerWindow.imageryLayers.add(new Cesium.ImageryLayer(new TencentImageryProvider(optionsT)))
        // 百度
        // var optionsBI = {
        //     style: 'img', // style: img、vec//地标 网路、normal、dark
        //     crs: 'WGS84' // 使用84坐标系,默认为:BD09
        // }
        // viewerWindow.imageryLayers.add(new Cesium.ImageryLayer(new BaiduImageryProvider(optionsBI)))
        var optionsB = {
            style: 'vec', // style: img、vec//地标 网路、normal、dark
            crs: 'WGS84', // 使用84坐标系,默认为:BD09
            maximumLevel: 18, // 设置最大级别
            // minimumLevel: 5   // 设置最小级别
        }
        viewerWindow.imageryLayers.add(new Cesium.ImageryLayer(new BaiduImageryProvider(optionsB)))

        viewerWindow.screenSpaceEventHandler.setInputAction(movement => {
            // 方式 1
            var cartesian = viewerWindow.camera.pickEllipsoid(movement.position, viewerWindow.scene.globe.ellipsoid);
            if (cartesian) {
                var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(8);
                var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(8);
                let height = this.viewerWindow.camera.positionCartographic.height.toFixed(2);
                // var point = GPS.bd09_To_Gcj02(latitudeString,longitudeString)
                // this.nowPosition = point.lon + ',' +  point.lat + "," + height
                // console.log(this.nowPosition,'this.nowPosition');
                this.nowPosition = longitudeString + ',' + latitudeString + "," + height
                this.nowPositionheight = height
                console.log("LongitudeAndLatitude: " + longitudeString + "," + latitudeString + "," + height);
                var h = this.viewerWindow.scene.camera.heading;
                var p = this.viewerWindow.scene.camera.pitch;
                var r = this.viewerWindow.scene.camera.roll;
                console.log("headingPitchRoll: " + h + "," + p + "," + r);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


        let pointDestination = Cesium.Cartesian3.fromDegrees(116.40069537, 39.96790221, 1500);//视野点

        viewerWindow.scene.camera.flyTo({
            destination: pointDestination,
            orientation: {
                heading: 6.283185307179586,
                pitch: -1.5707963267948966,
                roll: 0
            }
        })





        class ControlCamera {
            constructor(viewer) {
                this.timeInterval = 50
                this.viewer = viewer;
                this.deviceType = this.getDeviceType();
                this.ellipsoid = this.viewer.scene.globe.ellipsoid;
                this.initControl()
            }
            initControl() {
                this.downStart = 'touchstart';
                this.upEnd = 'touchend';
                if (this.deviceType == "电脑") {
                    this.downStart = "mousedown"
                    this.upEnd = "mouseup"
                }
            }
            enterKeyBoardMouseRoamingMode() {
                console.log('进入漫游模式');// 1.初始化相机漫游的标记
                this.flags = {
                    moveForward: false, // 是否向前移动
                    moveBackward: false, // 是否向后移动
                    moveLeft: false, // 是否向左移动
                    moveRight: false, // 是否向右移动
                    moveUp: false, // 是否向上移动
                    moveDown: false, // 是否向下移动
                }; // 相机漫游标记
                // 2.添加键盘监听事件
                // 键盘按下事件

                document.addEventListener('keydown', this.keyDown, false);
                // 键盘弹起事件
                document.addEventListener('keyup', this.keyUp, false);
                // // 3.添加渲染事件
                this.viewer.clock.onTick.addEventListener(this.renderEvent);
            }
            exitKeyBoardMouseRoamingMode() {
                console.log('退出漫游');
                // 1.移除键盘监听事件
                document.removeEventListener('keydown', this.keyDown, false);
                document.removeEventListener('keyup', this.keyUp, false);

                // 移除渲染事件
                this.viewer.clock.onTick.removeEventListener(this.renderEvent);

                this.flags = null;
            }
            keyDown = (event) => {
                let flagName = this.getFlagFromKeyCode(event.keyCode);
                if (typeof flagName !== 'undefined') {
                    this.flags[flagName] = true;
                }
            }/*** 键盘弹起*/
            keyUp = (event) => {
                let flagName = this.getFlagFromKeyCode(event.keyCode);
                if (typeof flagName !== 'undefined') {
                    this.flags[flagName] = false;
                }
            }/*** 渲染函数*/
            renderEvent = () => {
                // 声明变量,以下代码可能会多次用到
                let camera = this.viewer.camera;
                // 根据高度来决定镜头移动的速度
                let cameraHeight = this.ellipsoid.cartesianToCartographic(camera.position).height;
                let moveRate = cameraHeight / 50.0;
                if (this.flags.moveForward) { camera.moveForward(moveRate); }
                if (this.flags.moveBackward) { camera.moveBackward(moveRate); }
                if (this.flags.moveUp) { camera.moveUp(moveRate); }
                if (this.flags.moveDown) { camera.moveDown(moveRate); }
                if (this.flags.moveLeft) { camera.moveLeft(moveRate); }
                if (this.flags.moveRight) { camera.moveRight(moveRate); }
            }
            rotateCamera(n) {
                // 获取当前相机
                const camera = this.viewer.camera;

                // 获取当前相机的方向(heading)
                const currentHeading = camera.heading;

                // 设置旋转后的方向(顺时针旋转10度)
                const newHeading = currentHeading + Cesium.Math.toRadians(n);

                // 将相机旋转到新的方向
                camera.setView({
                    orientation: {
                        heading: newHeading,
                        pitch: camera.pitch,
                        roll: camera.roll,
                    },
                });
            }
            getFlagFromKeyCode(keyCode) {
                console.log("keyCode", keyCode);
                switch (keyCode) {
                    case 'W'.charCodeAt(0): return 'moveForward';
                    case 'S'.charCodeAt(0): return 'moveBackward';
                    case 'Q'.charCodeAt(0): return 'moveUp';
                    case 'E'.charCodeAt(0): return 'moveDown';
                    case 'D'.charCodeAt(0): return 'moveRight';
                    case 'A'.charCodeAt(0): return 'moveLeft';
                    default: return undefined;
                }
            }
            getDeviceType() {
                const userAgent = navigator.userAgent;
                console.log(userAgent);
                if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(userAgent)) {
                    return "平板";
                } else if (
                    /(mobi|opera mini|iphone|ipod|android|blackberry|windows phone)/i.test(
                        userAgent
                    )
                ) {
                    return "手机";
                } else {
                    return "电脑";
                }
            }
            addButtonTransformEvent(id, eventName) {
                let timer = null
                let button = document.querySelector(id);
                if (button) {
                    button.addEventListener(this.downStart, () => {
                        if (!this.flags) {
                            return
                        }
                        this.flags[eventName] = true
                        timer = setInterval(() => {
                            console.log('按钮被按下!');
                        }, this.timeInterval);
                    })
                    button.addEventListener(this.upEnd, () => {
                        if (!this.flags) {
                            return
                        }
                        clearInterval(timer)
                        this.flags[eventName] = false
                        console.log('按钮被松开!');
                    });
                }

            }

            addButtonRotationEvent(id, type = true, speed = 10) {
                let timerrotation = null
                let rotation = document.querySelector(id);
                if (rotation) {
                    rotation.addEventListener(this.downStart, () => {
                        if (!this.flags) {
                            return
                        }
                        timerrotation = setInterval(() => {
                            if (type) {
                                this.rotateCamera(speed)
                            } else {
                                this.rotateCamera(-speed)
                            }
                            console.log('按钮被按下!');
                        }, this.timeInterval);
                    })
                    rotation.addEventListener(this.upEnd, () => {
                        if (!this.flags) {
                            return
                        }
                        clearInterval(timerrotation)
                        console.log('按钮被松开!');
                    });

                }

            }
        }

        let controlCameraIncetance = new ControlCamera(viewerWindow)


        document.querySelector('.openC').addEventListener("click", () => {
            console.log(1);
            controlCameraIncetance.enterKeyBoardMouseRoamingMode()
            controlCameraIncetance.addButtonTransformEvent('.btn1', 'moveForward')
            controlCameraIncetance.addButtonTransformEvent('.btn2', 'moveBackward')
            controlCameraIncetance.addButtonTransformEvent('.btn3', 'moveLeft')
            controlCameraIncetance.addButtonTransformEvent('.btn4', 'moveRight')
            controlCameraIncetance.addButtonTransformEvent('.btn5', 'moveUp')
            controlCameraIncetance.addButtonTransformEvent('.btn6', 'moveDown')
            controlCameraIncetance.addButtonRotationEvent('.rotation1', true, 2)
            controlCameraIncetance.addButtonRotationEvent('.rotation2', false, 2)
        })
        document.querySelector('.closeC').addEventListener("click", () => {
            console.log(2);
            controlCameraIncetance.exitKeyBoardMouseRoamingMode()
        })








    </script>
</body>

</html>
  1. 同高度飞行,通过航向角计算封装
html 复制代码
<!DOCTYPE html>
<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">
    <script src="https://cesium.com/downloads/cesiumjs/releases/1.80/Build/Cesium/Cesium.js"></script>
    <link rel="stylesheet"
        href="https://cesium.com/downloads/cesiumjs/releases/1.80/Build/Cesium/Widgets/widgets.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/Turf.js/6.5.0/turf.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@dvgis/cesium-map/dist/cesium.map.min.js"></script>
    <title>Document</title>
    <style>
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        #cesiumContainer {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
        }

        .lonLat {
            position: fixed;
            width: 100%;
            bottom: 0;
            /* left: 50%; */
            color: aliceblue;
            text-align: center;
        }

        button:focus {
            outline: none;
            /* 取消选中时的轮廓边框 */
            box-shadow: none;
            /* 取消选中时的阴影效果 */

        }

        button {
            width: 80px;
            height: 50px;
            -webkit-user-select: none;
            /* Chrome, Safari, Opera */
            -moz-user-select: none;
            /* Firefox */
            -ms-user-select: none;
            /* Internet Explorer/Edge */
            user-select: none;
            /* 此规则适用于大多数浏览器 */
        }
    </style>
</head>

<body>
    <div id="cesiumContainer"></div>
    <div class="lonLat">
        <div>
            <button class="openC">开启</button>
            <button class="closeC">关闭</button>

        </div>
        <button class="btn1">前</button>
        <button class="btn2">后</button>
        <button class="btn3">左</button>
        <button class="btn4">右</button>
        <!-- <button class="btn5">上</button>
        <button class="btn6">下</button> -->
        <button class="rotation1">旋转heading+</button>
        <button class="rotation2">旋转heading-</button>
        <!-- <button class="rotation5">旋转pitch+</button>
        <button class="rotation6">旋转pitch-</button>
        <button class="rotation3">旋转roll+</button>
        <button class="rotation4">旋转roll-</button> -->
    </div>
    <script>
        // document.oncontextmenu = new Function("event.returnValue=false");
        // document.onselectstart = new Function("event.returnValue=false");
        // document.addEventListener("keydown", function (e) {
        //  		console.log(e.key);
        //         if (e.key == "F12") {
        //           e.preventDefault(); // 如果按下键F12,阻止事件
        //         }
        //     });

        // function getDeviceType() {
        //     const userAgent = navigator.userAgent;
        //     console.log(userAgent);
        //     if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(userAgent)) {
        //         return "平板";
        //     } else if (
        //         /(mobi|opera mini|iphone|ipod|android|blackberry|windows phone)/i.test(
        //             userAgent
        //         )
        //     ) {
        //         return "手机";
        //     } else {
        //         return "电脑";
        //     }
        // }

        // // 使用示例
        // const deviceType = getDeviceType();



        // console.log("设备类型:", deviceType);

        var viewer = new Cesium.Viewer("cesiumContainer", {


            geocoder: false, // 位置查找工具
            timeline: false, // 底部时间线
            homeButton: false, // 视角返回初始位置
            fullscreenButton: false, // 全屏
            animation: false, // 左下角仪表盘(动画器件)
            sceneModePicker: false, // 选择视角的模式(球体、平铺、斜视平铺)
            navigationHelpButton: false, //导航帮助按钮
            targetFrameRate: 30,
            imageryProvider: new Cesium.SingleTileImageryProvider({
                url: "data:image/gif;base64,R0lGODlhAQABAIAAAAUEBAAAACwAAAAAAQABAAACAkQBADs=",
            }),
            baseLayerPicker: false,
        });

        // 不显示底图
        // viewer.imageryLayers.get(0).show = false;
        // 去除logo
        viewer.cesiumWidget.creditContainer.style.display = "none";

        // 高德
        var optionsG = {
            style: 'img', // style: img、elec、cva//地标 网路
            crs: 'WGS84', // 使用84坐标系,默认为:GCJ02
            maximumLevel: 18, // 设置最大级别
            // minimumLevel: 5   // 设置最小级别
        }
        viewer.imageryLayers.add(new Cesium.ImageryLayer(new AmapImageryProvider(optionsG)))
        // // 腾讯
        // var optionsT = {
        //     style: 'img' //style: img、1:经典
        // }
        // viewer.imageryLayers.add(new Cesium.ImageryLayer(new TencentImageryProvider(optionsT)))
        // 百度
        // var optionsBI = {
        //     style: 'img', // style: img、vec//地标 网路、normal、dark
        //     crs: 'WGS84' // 使用84坐标系,默认为:BD09
        // }
        // viewer.imageryLayers.add(new Cesium.ImageryLayer(new BaiduImageryProvider(optionsBI)))
        var optionsB = {
            style: 'vec', // style: img、vec//地标 网路、normal、dark
            crs: 'WGS84', // 使用84坐标系,默认为:BD09
            maximumLevel: 18, // 设置最大级别
            // minimumLevel: 5   // 设置最小级别
        }
        viewer.imageryLayers.add(new Cesium.ImageryLayer(new BaiduImageryProvider(optionsB)))

        viewer.screenSpaceEventHandler.setInputAction(movement => {
            // 方式 1
            var cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
            if (cartesian) {
                var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                var longitudeString = Cesium.Math.toDegrees(cartographic.longitude).toFixed(8);
                var latitudeString = Cesium.Math.toDegrees(cartographic.latitude).toFixed(8);
                let height = this.viewer.camera.positionCartographic.height.toFixed(2);
                // var point = GPS.bd09_To_Gcj02(latitudeString,longitudeString)
                // this.nowPosition = point.lon + ',' +  point.lat + "," + height
                // console.log(this.nowPosition,'this.nowPosition');
                this.nowPosition = longitudeString + ',' + latitudeString + "," + height
                this.nowPositionheight = height
                console.log("LongitudeAndLatitude: " + longitudeString + "," + latitudeString + "," + height);
                var h = this.viewer.scene.camera.heading;
                var p = this.viewer.scene.camera.pitch;
                var r = this.viewer.scene.camera.roll;
                console.log("headingPitchRoll: " + h + "," + p + "," + r);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);


        let pointDestination = Cesium.Cartesian3.fromDegrees(116.40069537, 39.96790221, 1500);//视野点

        viewer.scene.camera.flyTo({
            destination: pointDestination,
            orientation: {
                heading: 6.283185307179586,
                pitch: -1.5707963267948966,
                roll: 0
            }
        })


        class CameraNavigation {
            constructor(viewer) {
                this.viewer = viewer;
                this.moveEndHandler = null;
                this.speed = null
                this.moveSpeed = null;
                this.height = null;
                this.buttonEvent = {};
                this.rotationSpeed = 2
                this.deviceType = this.getDeviceType();
                this.initControl()
               
                this.btnSAddEventListenerName = []
            }
            getDeviceType() {
                const userAgent = navigator.userAgent;
                console.log(userAgent);
                if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(userAgent)) {
                    return "平板";
                } else if (
                    /(mobi|opera mini|iphone|ipod|android|blackberry|windows phone)/i.test(
                        userAgent
                    )
                ) {
                    return "手机";
                } else {
                    return "电脑";
                }
            }
           initControl() {
                this.downStart = 'touchstart';
                this.upEnd = 'touchend';
                if (this.deviceType == "电脑") {
                    this.downStart = "mousedown"
                    this.upEnd = "mouseup"
                }
                console.log( this.upEnd, this.downStart);
            }

            setupEventListeners() {
                let currentHeightInit = this.viewer.camera.positionCartographic.height;
                this.height = Math.round(currentHeightInit);
                // 添加高度变化监听事件
                this.moveEndHandler = () => {
                    console.log(111);
                    const currentHeight = this.viewer.camera.positionCartographic.height;
                    this.height = Math.round(currentHeight);
                    if (!this.moveSpeed) {
                        this.speed = this.height/100
                    }else {
                        this.speed = this.moveSpeed
                    }
                }
                this.viewer.camera.moveEnd.addEventListener(this.moveEndHandler);
                console.log(this.height,'this.height');

            }
            setupCameraNavigation() {
                // 定义事件处理函数
                this.handleKeyDown =(event)=> {
                    console.log(event.key);
                    switch (event.key) {
                        // case 'ArrowUp' || 'w':
                        case 'w':
                            this.moveCamera("Up");
                            break;
                        // case 'ArrowDown' || 'd':
                        case 's':
                            this.moveCamera("Down");
                            break;
                        // case 'ArrowLeft' || 's':
                        case 'a':
                            this.moveCamera("Left");
                            break;
                        // case 'ArrowRight' || 'a':
                        case 'd':
                            this.moveCamera("Right");
                            break;
                        case 'q':
                            this.rotationCamera(10);
                            break;
                        case 'e':
                            this.rotationCamera(-10);
                            break;
                        default:
                            break;
                    }
                }

                // 添加键盘按下事件监听器
                document.addEventListener('keydown', this.handleKeyDown);
            }

            removeCameraNavigation() {
                this.btnSAddEventListenerName.forEach(ele=>{
                    document.querySelector(ele.id).removeEventListener(this.downStart,this.buttonEvent[ele.eventName].up, false)
                    document.querySelector(ele.id).removeEventListener(this.upEnd,this.buttonEvent[ele.eventName].upEnd, false)
                })
                // 移除键盘按下事件监听器
                if (this.handleKeyDown) {
                    document.removeEventListener('keydown', this.handleKeyDown);
                }
                // 取消高度变化监听事件
                this.viewer.camera.moveEnd.removeEventListener(this.moveEndHandler);
                this.btnSAddEventListenerName =[]
                this.buttonEvent = {}
            }

            moveCamera(type = 'Up') {
                // 获取当前Cesium相机
                const camera = this.viewer.camera;

                // 获取当前相机的位置和方向
                const currentPosition = camera.positionCartographic.clone();
                const currentHeading = camera.heading;

                // 定义移动的距离和方向
                const distance = this.speed; // 1000米示例距离
                let bearing = Cesium.Math.toDegrees(currentHeading); // 使用当前方向

                switch (type) {
                    case 'Up': // 向上移动
                        bearing = Cesium.Math.toDegrees(currentHeading)
                        break;
                    case 'Down': // 向下移动
                        bearing = Cesium.Math.toDegrees(currentHeading - Math.PI); // 使用当前方向
                        break;
                    case 'Left': // 向左移动
                        bearing = Cesium.Math.toDegrees(currentHeading - Math.PI / 2); // 使用当前方向
                        break;
                    case 'Right': // 向右移动
                        bearing = Cesium.Math.toDegrees(currentHeading + Math.PI / 2); // 使用当前方向
                        break;
                    default:
                        break;
                }
                // 使用Turf.js计算新位置
                const destination = turf.destination(
                    turf.point([Cesium.Math.toDegrees(currentPosition.longitude), Cesium.Math.toDegrees(currentPosition.latitude)]),
                    distance,
                    bearing,
                    { units: 'meters' }
                );
                // 将新位置转换为Cesium坐标
                const newCartesian = Cesium.Cartesian3.fromDegrees(destination.geometry.coordinates[0], destination.geometry.coordinates[1], this.height);

                // 设置相机位置
                camera.position = newCartesian;
            }
            rotationCamera(n) {

                // 获取当前相机
                const camera = this.viewer.camera;

                // 获取当前相机的方向(heading)
                const currentHeading = camera.heading;

                // 设置旋转后的方向(顺时针旋转10度)
                const newHeading = currentHeading + Cesium.Math.toRadians(n);

                // 将相机旋转到新的方向
                camera.setView({
                    orientation: {
                        heading: newHeading,
                        pitch: camera.pitch,
                        roll: camera.roll,
                    },
                });
            }
            addButtonTransformEvent(id, eventName) {
                let timer = null
                let button = document.querySelector(id);
                let eventNameString  =eventName;
                let findObj = this.btnSAddEventListenerName.find(ele=>ele.id== id)
                if (findObj) {
                    return
                }{
                    this.btnSAddEventListenerName.push({
                        id:id,
                        eventName:eventName
                    })
                }
                if (button) {
                    this.buttonEvent[eventName] = {}
                    this.buttonEvent[eventName].up =   () => {
                        if (timer) {
                            clearInterval(timer)
                        }
                        
                        timer = setInterval(() => {
                            console.log('按钮被按下!');
                            if (eventNameString == "moveForward") {
                                this.moveCamera("Up");
                            }else if (eventNameString == "moveBackward") {
                                this.moveCamera("Down");
                            }
                            else if (eventNameString == "moveLeft") {
                                this.moveCamera("Left");
                            }
                            else if (eventNameString == "moveRight") {
                                this.moveCamera("Right");
                            }
                            else if (eventNameString == "rotation+") {
                                this.rotationCamera(this.rotationSpeed) ;
                            }
                            else if (eventNameString == "rotation-") {
                                this.rotationCamera(-this.rotationSpeed) ;
                            }
                        }, 30);
                        console.log(eventNameString, 'eventName');
                    }
                    button.addEventListener(this.downStart,this.buttonEvent[eventName].up, false)
                    this.buttonEvent[eventName].upEnd = () => {
                        clearInterval(timer)
                        console.log('按钮被松开!');
                    }
                    button.addEventListener(this.upEnd,this.buttonEvent[eventName].upEnd, false);
                }

            }
        }

        // 使用示例
        const cameraNavigation = new CameraNavigation(viewer);
        document.querySelector('.openC').addEventListener("click", () => {
            cameraNavigation.setupCameraNavigation()
            // cameraNavigation.moveSpeed = 100 // 移动速度 默认是当前相机高度/100的速度
            cameraNavigation.rotationSpeed = 0.2// 旋转速度 默认是2度每次
            cameraNavigation.setupEventListeners();
            cameraNavigation.addButtonTransformEvent('.btn1', 'moveForward')
            cameraNavigation.addButtonTransformEvent('.btn2', 'moveBackward')
            cameraNavigation.addButtonTransformEvent('.btn3', 'moveLeft')
            cameraNavigation.addButtonTransformEvent('.btn4', 'moveRight')
            cameraNavigation.addButtonTransformEvent('.rotation1', 'rotation+')
            cameraNavigation.addButtonTransformEvent('.rotation2', 'rotation-')
        });

        document.querySelector('.closeC').addEventListener("click", () => {
            cameraNavigation.removeCameraNavigation();
        });
    </script>
</body>

</html>
相关推荐
CES_Asia1 天前
工信部“人工智能+”制造行动点亮CES Asia 2025
人工智能·科技·数码相机·制造·智能音箱·智能手表
只待花开2 天前
ROS2 python编写 intel realsense D405相机节点通过launch.py启动多个相机并发送图像话题,基于pyrealsense2库
数码相机
KeyPan3 天前
【ORB-SLAM3:相机针孔模型和相机K8模型】
数码相机
千穹凌帝3 天前
基于深度学习多图像融合的屏幕缺陷检测方案
人工智能·深度学习·数码相机
传说故事4 天前
相机内外参知识
数码相机·相机·相机参数
妄想出头的工业炼药师4 天前
imu相机EKF
数码相机
合方圆~小文4 天前
工业摄像机基于电荷耦合器件的相机
人工智能·深度学习·数码相机·目标检测
资源补给站4 天前
大恒相机开发(1)—Python调用采集彩色图像并另存为本地
开发语言·python·数码相机
OAK中国_官方5 天前
四相机设计实现全向视觉感知的开源空中机器人无人机
数码相机·机器人·无人机
s_daqing5 天前
解锁BL后的K40降级
数码相机