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

React + Mapbox: Sample implementation of `getRenderedFeatures` in Deck.gl?


I have a project using a React, Mapbox, and Deck.gl stack. I'm trying to query the features on a styled map but am having trouble implementing Deck.gl's getRenderedFeatures function, even after looking at the documentation.

My current React component:

<DeckGL
          {...deckGLProps}
          layers={layers}
          onViewportChange={() => console.log(mapRef)}
          ref={mapRef}
          getRenderedFeatures={(e) => console.log(e)}
        >
          <StaticMap
            ref={mapRef}
            visible={!level}
            {...staticMapProps}
            {...viewport}
            mapStyle={mapStyle[0]}
          />
        </DeckGL>

I understand that querying getRenderedFeatures on onViewportLoad is recommended, but I can't find an implementation that works.

Does anyone have a working implementation of getRenderedFeatures or a link to better documentation on the function?


Solution

  • Are you using MVTLayer right?

    getRenderedFeatures is a method of MVTLayer class, you need to access it from here, not from the deck instance.

    The logic could be:

    1. Render the MVTLayer
    2. Listen onViewStateChange from the deck instance with some debounce
    3. Then call getRenderedFeatures

    Something like:

    function debounce(fn, ms) {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          timer = null;
          fn.apply(this, args);
        }, ms);
      };
    }
    
    const YourMVTLayer = new MVTLayer({ ... });
    
    function getViewportFeatures() {
      const viewportFeatures = YourMVTLayer.getRenderedFeatures();
      console.log(viewportFeatures);
    }
    
    // render
    <DeckGL
     ...
     layers={[YourMVTLayer]}
     onViewportChange={debounce(getViewportFeatures, 500)}
    />
    

    Here another example using the scripting API