<!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>
</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
}
})
let ellipsoid = viewer.scene.globe.ellipsoid;
// 声明相机漫游标记
let flags = null;/*** 进入键盘漫游模式*/
function enterKeyBoardMouseRoamingMode() {
console.log('进入漫游模式');// 1.初始化相机漫游的标记
flags = {
moveForward: false, // 是否向前移动
moveBackward: false, // 是否向后移动
moveLeft: false, // 是否向左移动
moveRight: false, // 是否向右移动
moveUp: false, // 是否向上移动
moveDown: false, // 是否向下移动
}; // 相机漫游标记
// 2.添加键盘监听事件
// 键盘按下事件
document.addEventListener('keydown', keyDown, false);
// 键盘弹起事件
document.addEventListener('keyup', keyUp, false);
// 3.添加渲染事件
viewer.clock.onTick.addEventListener(renderEvent);
}// DOM添加一个开启键盘鼠标漫游模式的按钮,使用绝对定位放在屏幕左上角,用于测试
let downStart = 'touchstart';
let upEnd = 'touchend';
if (deviceType == "电脑") {
downStart = "mousedown"
upEnd = "mouseup"
}
let button1 = document.querySelector('.btn1');
let timer1 = null
button1.addEventListener(downStart, function () {
if (!flags) {
return
}
flags.moveForward = true
timer1 = setInterval(() => {
console.log('按钮被按下!');
}, 100);
})
button1.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timer1)
flags.moveForward = false
console.log('按钮被松开!');
});
let button2 = document.querySelector('.btn2');
let timer2 = null
button2.addEventListener(downStart, function () {
if (!flags) {
return
}
flags.moveBackward = true
timer2 = setInterval(() => {
console.log('按钮被按下!');
}, 100);
})
button2.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timer2)
flags.moveBackward = false
console.log('按钮被松开!');
});
let button3 = document.querySelector('.btn3');
let timer3 = null
button3.addEventListener(downStart, function () {
if (!flags) {
return
}
flags.moveLeft = true
timer3 = setInterval(() => {
console.log('按钮被按下!');
}, 100);
})
button3.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timer3)
flags.moveLeft = false
console.log('按钮被松开!');
});
let button4 = document.querySelector('.btn4');
let timer4 = null
button4.addEventListener(downStart, function () {
if (!flags) {
return
}
flags.moveRight = true
timer4 = setInterval(() => {
console.log('按钮被按下!');
}, 100);
})
button4.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timer4)
flags.moveRight = false
console.log('按钮被松开!');
});
let button5 = document.querySelector('.btn5');
let timer5 = null
button5.addEventListener(downStart, function () {
if (!flags) {
return
}
flags.moveUp = true
timer5 = setInterval(() => {
console.log('按钮被按下!');
}, 100);
})
button5.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timer5)
flags.moveUp = false
console.log('按钮被松开!');
});
let button6 = document.querySelector('.btn6');
let timer6 = null
button6.addEventListener(downStart, function () {
if (!flags) {
return
}
flags.moveDown = true
timer6 = setInterval(() => {
console.log('按钮被按下!');
}, 100);
})
button6.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timer6)
flags.moveDown = false
console.log('按钮被松开!');
});
let rotation1 = document.querySelector('.rotation1');
let timerrotation1 = null
rotation1.addEventListener(downStart, function () {
if (!flags) {
return
}
timerrotation1 = setInterval(() => {
rotateCamera(5)
console.log('按钮被按下!');
}, 100);
})
rotation1.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timerrotation1)
console.log('按钮被松开!');
});
let rotation2 = document.querySelector('.rotation2');
let timerrotation2 = null
rotation2.addEventListener(downStart, function () {
if (!flags) {
return
}
timerrotation2 = setInterval(() => {
rotateCamera(-5)
console.log('按钮被按下!');
}, 100);
})
rotation2.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timerrotation2)
console.log('按钮被松开!');
});
let rotation3 = document.querySelector('.rotation3');
let timerrotation3 = null
rotation3.addEventListener(downStart, function () {
if (!flags) {
return
}
timerrotation3 = setInterval(() => {
setCameraRoll(5)
console.log('按钮被按下!');
}, 100);
})
rotation3.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timerrotation3)
console.log('按钮被松开!');
});
let rotation4 = document.querySelector('.rotation4');
let timerrotation4 = null
rotation4.addEventListener(downStart, function () {
if (!flags) {
return
}
timerrotation4 = setInterval(() => {
setCameraRoll(-5)
console.log('按钮被按下!');
}, 100);
})
rotation4.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timerrotation4)
console.log('按钮被松开!');
});
let rotation5 = document.querySelector('.rotation5');
let timerrotation5 = null
rotation5.addEventListener(downStart, function () {
if (!flags) {
return
}
timerrotation5 = setInterval(() => {
setCameraPitch(5)
console.log('按钮被按下!');
}, 100);
})
rotation5.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timerrotation5)
console.log('按钮被松开!');
});
let rotation6 = document.querySelector('.rotation6');
let timerrotation6 = null
rotation6.addEventListener(downStart, function () {
if (!flags) {
return
}
timerrotation6 = setInterval(() => {
setCameraPitch(-5)
console.log('按钮被按下!');
}, 100);
})
rotation6.addEventListener(upEnd, function () {
if (!flags) {
return
}
clearInterval(timerrotation6)
console.log('按钮被松开!');
});
let enterButton = document.createElement('button');
enterButton.innerText = '开启';
enterButton.style.position = 'absolute';
enterButton.style.left = '20px';
enterButton.style.top = '20px';
enterButton.onclick = enterKeyBoardMouseRoamingMode;
document.body.appendChild(enterButton);/*** 退出键盘漫游模式*/
function exitKeyBoardMouseRoamingMode() {
console.log('退出漫游');
// 1.移除键盘监听事件
document.removeEventListener('keydown', keyDown, false);
document.removeEventListener('keyup', keyUp, false);
// 2.移除渲染事件
viewer.clock.onTick.removeEventListener(renderEvent);
}// DOM添加一个关闭键盘鼠标漫游模式的按钮,使用绝对定位放在屏幕左上角,用于测试
let exitButton = document.createElement('button');
exitButton.innerText = '关闭';
exitButton.style.position = 'absolute';
exitButton.style.left = '120px';
exitButton.style.top = '20px';
exitButton.onclick = exitKeyBoardMouseRoamingMode;
document.body.appendChild(exitButton);/*** 键盘按下*/
function keyDown(event) {
let flagName = getFlagFromKeyCode(event.keyCode);
if (typeof flagName !== 'undefined') { flags[flagName] = true; }
}/*** 键盘弹起*/
function keyUp(event) {
let flagName = getFlagFromKeyCode(event.keyCode);
if (typeof flagName !== 'undefined') { flags[flagName] = false; }
}/*** 渲染函数*/
console.log(viewer.camera, 'cameracameracamera');
function renderEvent() {
// 声明变量,以下代码可能会多次用到
let camera = viewer.camera;
// 根据高度来决定镜头移动的速度
let cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
let moveRate = cameraHeight / 50.0;
if (flags.moveForward) { camera.moveForward(moveRate); }
if (flags.moveBackward) { camera.moveBackward(moveRate); }
if (flags.moveUp) { camera.moveUp(moveRate); }
if (flags.moveDown) { camera.moveDown(moveRate); }
if (flags.moveLeft) { camera.moveLeft(moveRate); }
if (flags.moveRight) { camera.moveRight(moveRate); }
}/*** 从键盘码获取flag标记*/
function 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;
}
}
function rotateCamera(n) {
// 获取当前相机
const camera = 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,
},
});
}
function setCameraPitch(pitch) {
const camera = viewer.camera;
// 获取当前相机的方向(heading 和 pitch)
const currentHeading = camera.heading;
const currentPitch = camera.pitch;
console.log(currentPitch,'currentPitch');
// 将相机的方向设置为新的 roll,保持 heading 和 pitch 不变
camera.setView({
orientation: {
heading: currentHeading,
pitch: currentPitch + Cesium.Math.toRadians(pitch),
roll: camera.roll,
},
});
}
function setCameraRoll(roll) {
const camera = viewer.camera;
// 获取当前相机的方向(heading 和 pitch)
const currentHeading = camera.heading;
const currentPitch = camera.pitch;
// 将相机的方向设置为新的 roll,保持 heading 和 pitch 不变
camera.setView({
orientation: {
heading: currentHeading,
pitch: currentPitch,
roll: camera.roll + Cesium.Math.toRadians(roll), // 将度数转换为弧度
},
});
}
function rotateCameraSmoothly(degreesPerSecond) {
const camera = viewer.camera;
const startTime = Date.now();
const duration = 1000; // 旋转的总时间(毫秒)
function updateCamera() {
const currentTime = Date.now();
const elapsedTime = currentTime - startTime;
const progress = elapsedTime / duration;
// 如果旋转时间超过总时间,则停止旋转
if (progress >= 1) {
return;
}
// 计算当前的旋转角度(弧度)
const currentHeading = camera.heading;
const targetHeading = currentHeading + Cesium.Math.toRadians(degreesPerSecond * (elapsedTime / 1000));
// 将相机旋转到新的方向
camera.setView({
orientation: {
heading: targetHeading,
pitch: camera.pitch,
roll: camera.roll,
},
});
// 继续更新相机的角度
requestAnimationFrame(updateCamera);
}
// 开始更新相机
requestAnimationFrame(updateCamera);
}
</script>
</body>
</html>
cesium 键盘控制漫游
最新推荐文章于 2024-04-01 15:15:41 发布