首页 > 解决方案 > DeckGL & Mapbox:如何在地图移动时访问 ref 元素?

问题描述

console.log每次我在地图上移动时,我都会尝试在我的 React 应用程序中找到 Mapbox 地图的边界。

这是我目前的尝试:

return (
    <>
      <DeckGL
        layers={layers}
        initialViewState={INITIAL_VIEW_STATE}
        controller={true}
        onViewStateChange={stateChangeFunc}
      >
        <ReactMapGL
          reuseMaps
          mapStyle={mapStyle}
          preventStyleDiffing={true}
          ref={(ref) => console.log(ref.getMap().getBounds())}
          mapboxApiAccessToken={token}
        />
      </DeckGL>
    </>
  );

地图加载时会打印边界,但在地图上移动时打印时遇到问题。prop我应该使用它来访问此功能吗?装ref={(ref) => console.log(ref.getMap().getBounds())}进去DeckGL是不行的。是否有相当于onViewStateChangefor的道具ReactMapGL?这可能允许我创建一个打印出ref.

标签: reactjsmapboxmapbox-gl-jsdeck.glreact-map-gl

解决方案


你可以试试:

  • 直接从甲板上收听onViewStateChange(建议使用一些去抖动)
  • 使用权viewState
  • 使用类getBounds中的方法WebMercatorViewport
import DeckGL, {WebMercatorViewport} from 'deck.gl';

function debounce(fn, ms) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, ms);
  };
}

function handleViewStateChange({ viewState }) {
  const bounds = new WebMercatorViewport(viewState).getBounds();
  console.log(bounds);
};

<DeckGL
  ...
  onViewStateChange={debounce(handleViewStateChange, 500)}
/>

推荐阅读