DeckGL结合Mapbox开发时,地图移动过程中如何访问ref获取地图边界?
解决方法
你原来的实现仅在加载时打印边界,是因为组件的ref回调只会在组件挂载、卸载两个节点执行,地图移动过程中不会触发ref的重新赋值,所以打印逻辑不会执行。
ReactMapGL提供了和DeckGL onViewStateChange 功能等价的回调属性:
onMove:地图视图变化过程中(平移、缩放、旋转等操作进行时)实时触发onMoveEnd:地图视图变化结束(操作停止后)触发
你可以按如下方式修改代码即可实现需求:
import { useRef } from 'react'; // 组件内部逻辑 const mapRef = useRef(null); // 地图移动时的回调函数 const handleMapMove = () => { if (!mapRef.current) return; const currentBounds = mapRef.current.getMap().getBounds(); console.log('当前地图边界:', currentBounds); }; return ( <> <DeckGL layers={layers} initialViewState={INITIAL_VIEW_STATE} controller={true} onViewStateChange={stateChangeFunc} > <ReactMapGL reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} ref={mapRef} onMove={handleMapMove} mapboxApiAccessToken={token} /> </DeckGL> </> );
如果需要仅在地图移动结束后才打印边界,把onMove替换为onMoveEnd即可。
补充优化点:如果你的DeckGL和ReactMapGL已经做了视图同步,也可以直接在DeckGL的
onViewStateChange回调中执行打印逻辑,不需要额外绑定ReactMapGL的回调,性能表现会更好。
内容的提问来源于stack exchange,提问作者mmz
相关产品推荐
相关产品推荐

