1.主方法
/**
* 在范围内移动地图, 超出时按提供的回调返回主视角, 组件卸载时一定要用返回的函数取消监听
* @param {*} range 范围
* @param {*} cb 返回主视角的函数
* @param {*} maximumZoomDistance 最大高度
* @param {*} minimumZoomDistance 最小高度
*/
moveOnRange(range, cb, maximumZoomDistance, minimumZoomDistance) {
const originMax = viewer.scene.screenSpaceCameraController.maximumZoomDistance//变焦时相机位置的最大大小。默认为无穷大
const originMin = viewer.scene.screenSpaceCameraController.minimumZoomDistance
if (maximumZoomDistance) viewer.scene.screenSpaceCameraController.maximumZoomDistance = maximumZoomDistance;//为了可以看到变焦时的超出范围的效果
if (minimumZoomDistance) viewer.scene.screenSpaceCameraController.minimumZoomDistance = minimumZoomDistance;
if (typeof cb !== 'function') return
const throttlingCb = throttling(cb, 2000)
const func = function () {
//计算镜头范围方法(椭球上的近似可见矩形),该方法会计算当前镜头地理坐标(弧度)范围并返回west,east,north,south 4个范围参数
let rectangle = viewer.camera.computeViewRectangle();
// 弧度转为经纬度,west为左(西)侧边界的经度,以下类推
let west = Cesium.Math.toDegrees(rectangle.west)
let north = Cesium.Math.toDegrees(rectangle.north)
let east = Cesium.Math.toDegrees(rectangle.east)
let south = Cesium.Math.toDegrees(rectangle.south)
//如果视角超出设置范围则跳转视角
if (west < range.west || north > range.north || east > range.east || south < range.south) {
//这里可以添加控制地球的是否允许平移等等
throttlingCb()
} else {
//这里可以添加控制地球的是否允许平移等等
}
}
//实时监测镜头范围(该方法会一直调用)
viewer.scene.preRender.addEventListener(func)
return () => {
viewer.scene.screenSpaceCameraController.maximumZoomDistance = originMax;
viewer.scene.screenSpaceCameraController.minimumZoomDistance = originMin;
viewer.scene.preRender.removeEventListener(func)
}
}
}
2.throttlingCb()(节流调用返回主视角的方法,不然响应跟不上触发频率)
let throttling = function (callback, delay) {
let time = 0;
return function () {
let now = new Date()
if (now - time > delay) {
console.log('this---',this);
callback.call(this)
time = now
}
}
}
3.调用
moveOnRange({
east: 115.35,
north: 23.01,
south: 22.25,
west: 113.53,
}, ()=>this.backHome(), 200000)