0

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.

mmz
  • 1,011
  • 1
  • 8
  • 21

1 Answers1

1

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)}
/>
AdriSolid
  • 2,570
  • 1
  • 7
  • 17