【问题标题】:DeckGL & Mapbox: How access ref element on map movement?DeckGL & Mapbox:如何在地图移动时访问 ref 元素?
【发布时间】:2021-07-17 20:27:33
【问题描述】:

每次我在地图上移动时,我都会尝试在我的 React 应用程序中 console.log 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) =&gt; console.log(ref.getMap().getBounds())} 放入DeckGL 不起作用。对于ReactMapGL,是否有相当于onViewStateChange 的道具?这可能允许我创建一个打印出ref 的函数。

【问题讨论】:

    标签: reactjs mapbox mapbox-gl-js deck.gl react-map-gl


    【解决方案1】:

    你可以试试:

    • 直接从卡座收听onViewStateChange(建议使用一些去抖)
    • 访问viewState
    • 使用WebMercatorViewport类中的getBounds方法
    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)}
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 2015-01-24
      • 1970-01-01
      • 2023-03-30
      • 2022-08-19
      相关资源
      最近更新 更多