不使用npm与ES6模块时如何在deck.gl中定时触发fitBounds适配边界
解决方案
方案1:复用现有mapboxgl依赖计算适配参数(推荐)
你之前调用map.fitBounds无响应是因为你给mapbox实例设置了interactive: false,且你的deck和mapbox视图是独立维护的,我们无需让mapbox地图本身跳转,只需要用mapbox内置能力算出适配所需的视图参数,再同步给deckGL即可:
// 替换为你计算好的边界,格式为[[最小经度, 最小纬度], [最大经度, 最大纬度]] const dataBounds = [[minLng, minLat], [maxLng, maxLat]]; // 替换为你的deckGL容器DOM节点 const deckContainer = document.getElementById('deck容器的ID'); const containerWidth = deckContainer.offsetWidth; const containerHeight = deckContainer.offsetHeight; // 用mapboxgl内置方法计算适配参数,完全不影响现有map实例 const transform = new mapboxgl.Transform(); transform.resize(containerWidth, containerHeight); const fitResult = transform.fitBounds(dataBounds, { padding: 20, // 自定义边界与容器的边距,单位为px maxZoom: 18 // 自定义最大缩放等级,避免边界过小导致缩放过高 }); // 将计算出的参数更新到deckGL即可完成视图适配 deckMap.setProps({ initialViewState: { longitude: fitResult.center.lng, latitude: fitResult.center.lat, zoom: fitResult.zoom } });
该方案完全使用你已经引入的mapboxgl依赖,无需额外导入任何包,也不需要修改现有代码的模块配置。
方案2:纯JS实现适配计算(无任何额外依赖)
如果方案1因本地mapboxgl版本问题不可用,可直接使用从deckGL官方逻辑简化的适配计算函数,无需导入任何依赖:
// 直接将这段工具函数复制到你的代码中即可使用 function calculateFitViewState(bounds, containerWidth, containerHeight, options = {}) { const { padding = 20, maxZoom = 18 } = options; const [minLng, minLat, maxLng, maxLat] = [bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1]]; // 计算边界中心点 const centerLng = (minLng + maxLng) / 2; const centerLat = (minLat + maxLat) / 2; // 计算经纬度跨度对应的缩放等级 const latDiff = maxLat - minLat; const lngDiff = maxLng - minLng; const latZoom = Math.log(Math.PI * containerHeight / (256 * latDiff)) / Math.LN2; const lngZoom = Math.log(Math.PI * containerWidth / (256 * lngDiff)) / Math.LN2; const finalZoom = Math.min(latZoom, lngZoom, maxZoom) - Math.log2(1 + padding / Math.min(containerWidth, containerHeight)); return { longitude: centerLng, latitude: centerLat, zoom: Math.max(finalZoom, 0) } } // 调用示例 const dataBounds = [[minLng, minLat], [maxLng, maxLat]]; const deckContainer = document.getElementById('deck容器的ID'); const fitViewState = calculateFitViewState(dataBounds, deckContainer.offsetWidth, deckContainer.offsetHeight, { padding: 20 }); deckMap.setProps({ initialViewState: fitViewState });
内容的提问来源于stack exchange,提问作者Human_BetaRelease
相关产品推荐
相关产品推荐

