I am new to Cesium, and I want to switch views while retaining the exact position. Initially, my viewer is set to 3D. When I switch from 3D to 2D, it works fine, and I maintain the exact location. However, when I switch from 3D to Columbus view, I lose the exact location, and the same happens when I switch back to 3D or from 2D to 3D; the location is lost. I want to know how to switch between views while preserving the current location."
function saveCameraPosition() {
var cameraPosition = viewer.camera.positionWC;
var cameraDirection = viewer.camera.direction;
var cameraUp = viewer.camera.up;
var cameraRight = viewer.camera.right;
var cameraProjection = viewer.camera.projection;
var cameraData = {
position: cameraPosition,
direction: cameraDirection,
up: cameraUp,
right: cameraRight,
projection: cameraProjection // Store the projection property
};
localStorage.setItem(‘cameraData’, JSON.stringify(cameraData));
}
viewer.scene.morphStart.addEventListener(function () {
saveCameraPosition();
});
// Function to restore the camera position from localStorage
function restoreCameraPosition() {
var cameraData = localStorage.getItem(‘cameraData’);
if (cameraData) {
cameraData = JSON.parse(cameraData);
// Check the current view mode and set the camera properties accordingly
var currentViewMode = viewer.scene.mode;
if (currentViewMode === Cesium.SceneMode.SCENE3D) {
// For 3D view, only set the camera position and projection
viewer.camera.setView({
destination: cameraData.position,
projection: cameraData.projection
});
} else if (currentViewMode === Cesium.SceneMode.SCENE2D) {
viewer.camera.setView({
destination: cameraData.position,
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-90),
roll: 0.0
},
projection: cameraData.projection // Add the projection property
});
}else if (currentViewMode === Cesium.SceneMode.COLUMBUS_VIEW) {
// For Columbus view, set camera position and orientation (heading, pitch, roll)
viewer.camera.setView({
destination: cameraData.position,
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-30),
roll: 0.0
},
projection: cameraData.projection
});
}
}
}
viewer.scene.morphComplete.addEventListener(function () {
restoreCameraPosition();
});