1. 程式人生 > 其它 >cesium 平滑切換二三維

cesium 平滑切換二三維

很多人用sceneMode 來進行二三維切換 ,其實這樣不好用,位置什麼的 圖層狀態都不好繫結,給人體驗非常差
對於arcgis 引擎 可以鎖視角實現平滑切換,mapbox 引擎也可以鎖視角實現,但是對於cesium 也是可以的

首先我們要知道獲取中心點方法

  • function getCenter(viewer: any) {
  • // debugger
  • const scene = viewer.scene;
  • const target = pickCenterPoint(scene);
  • let bestTarget = target;
  • const globe = scene.globe;
  • const carto = scene.camera.positionCartographic.clone();
  • const height = globe.getHeight(carto);
  • carto.height = height || 0;
  • bestTarget = Cesium.Ellipsoid.WGS84.cartographicToCartesian(carto);
  • const result = formatPosition(bestTarget);
  • // 獲取地球中心點世界位置 與 攝像機的世界位置 之間的距離
  • const distance = Cesium.Cartesian3.distance(bestTarget, viewer.scene.camera.positionWC);
  • result.cameraZ = distance;
  • return result;
  • }
  • function pickCenterPoint(scene: any) {
  • const canvas = scene.canvas;
  • const center = new Cesium.Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2);
  • const ray = scene.camera.getPickRay(center);
  • const target = scene.globe.pick(ray, scene);
  • return target || scene.camera.pickEllipsoid(center);
  • }
  • function formatPosition(position) {
  • const carto = Cesium.Cartographic.fromCartesian(position);
  • const result = {};
  • result.y = formatNum(Cesium.Math.toDegrees(carto.latitude), 6);
  • result.x = formatNum(Cesium.Math.toDegrees(carto.longitude), 6);
  • result.z = formatNum(carto.height, 2);
  • return result;
  • }
  • function formatNum(num, digits) {
  • return Number(num.toFixed(digits || 0));
  • }

第二我們要知道螢幕中心點位置

  • function getScreenCenter(_viewer: any) {
  • const viewer = _viewer;
  • const result = viewer.camera.pickEllipsoid(new Cesium.Cartesian2(viewer.canvas.clientWidth / 2, viewer.canvas.clientHeight / 2));
  • const curPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(result);
  • const lon = (curPosition.longitude * 180) / Math.PI;
  • const lat = (curPosition.latitude * 180) / Math.PI;
  • const height = curPosition.height;
  • return {
  • x: lon,
  • y: lat
  • };
  • }

下面我們來定義呼叫切換二三維的方法, 其中mapType 我定義為mapView和sceneView型別, 哈哈學習arcgis模式
```javascript

type mapType = 'mapView' | 'sceneView';

public changeSV23D(viewer: any, type: mapType) {
const viewer = viewer;
const result: any = getCenter(viewer);
const curPosition = getScreenCenter(viewer);
const center = Cesium.Cartesian3.fromDegrees(curPosition.x, curPosition.y);
if (type === 'sceneView') {
if (viewer.view === 'sceneView') {
return;
}
viewer.scene.screenSpaceCameraController.enableTilt = true;
viewer.view = 'sceneView';
let x = -90;
let pitch;
const range = result.cameraZ * 1.2;

更多參考https://xiaozhuanlan.com/topic/7459016328