Cesium获取摄像机位置,并在项目打开的时候自动移动过去
1. 背景
在使用cesium的库的时候发现如果通过获取当前摄像机的heading_pitch_roll之后,通过heading_pitch_roll 和经纬度,调用setView方法,摄像机的roll和设置的roll并无法保证一致,导致无法稳定让相机在每次打开项目的时候处于同一位置。为了解决此问题,最后解决方案如下:
2. 解决方案
获取摄像机的positionWC,up和direction, 通过这三个属性确定摄像机在三维空间的绝对位置,在下次打开项目的时候,通过这三个属性设置相机位置,保证相机位置一致
2.1 获取相机当前位置
inspectCamera = () => {
const position = viewer.camera.positionWC.clone();
const up = viewer.camera.up.clone();
const direction = viewer.camera.direction.clone();
const cam = viewer.camera;
const camPos = viewer.camera.positionCartographic;
const center_lat = camPos.latitude * (180 / Math.PI);
const center_lng = camPos.longitude * (180 / Math.PI);
const heading = Cesium.Math.toDegrees(cam.heading);
const pitch = Cesium.Math.toDegrees(cam.pitch);
const roll = Cesium.Math.toDegrees(cam.roll);
const result = {
cartesian_degrees: {
center_lat: Number(center_lat.toFixed(7)),
center_lng: Number(center_lng.toFixed(7)),
height: Number(camPos.height.toFixed(1)),
},
heading_pitch_roll: {
heading: Number(heading.toFixed(10)),
pitch: Number(pitch.toFixed(10)),
roll: Number(roll.toFixed(10)),
},
positionWC: {
x: Number(position.x.toFixed(20)),
y: Number(position.y.toFixed(20)),
z: Number(position.z.toFixed(20)),
},
up: {
x: Number(up.x.toFixed(20)),
y: Number(up.y.toFixed(20)),
z: Number(up.z.toFixed(20)),
},
direction: {
x: Number(direction.x.toFixed(20)),
y: Number(direction.y.toFixed(20)),
z: Number(direction.z.toFixed(20)),
},
};
console.log('result:', result);
return result;
}
2.2 设置相机在三维空间的位置和角度
var init_view_params = {
"positionWC": {
"x": -2502076.6774347303,
"y": -4655117.708789966,
"z": 3560673.8364293934
},
"up": {
"x": 0.03997612092939651,
"y": -0.2768413582376877,
"z": 0.9600837318299642
},
"direction": {
"x": 0.610163988910468,
"y": 0.7676610770449577,
"z": 0.1959499360220417
}
}
// Fly the camera to the given longitude, latitude, and height.
let positionWC = init_view_params.positionWC;
let direction = init_view_params.direction;
let up = init_view_params.up;
let pos = new Cesium.Cartesian3(positionWC.x, positionWC.y, positionWC.z);
let dir = new Cesium.Cartesian3(direction.x, direction.y, direction.z);
let upValue = new Cesium.Cartesian3(up.x, up.y, up.z);
let homeCameraView = {
destination: pos,
orientation: {
direction: dir,
up: upValue
}
}
viewer.scene.camera.setView(homeCameraView);