Search code examples
reactjsmapboxmapbox-gl-jsdeck.glreact-map-gl

DeckGL & Mapbox: How access ref element on map movement?


I'm trying to console.log the bounds of a Mapbox map in my React app every time I move around the map.

Here's my current attempt:

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>
    </>
  );

The bounds are printed when the map loads, but I'm having trouble printing when moving around the map. Is there a prop that I should use to access this functionality? Putting ref={(ref) => console.log(ref.getMap().getBounds())} in DeckGL doesn't work. Is there a prop equivalent to onViewStateChange for ReactMapGL? That might allow me to create a function that prints out the ref.


Solution

  • You can try:

    • Listen onViewStateChange directly from deck (recommended using some debounce)
    • Access viewState
    • Use getBounds method from WebMercatorViewport class
    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)}
    />