2

I'm quite new to React and JavaScript, am trying to write a queryRenderedFeatures filter for my React Hooks project using React-Map-gl.

The project has a huge list of data, and what I'd like to do is only filtering the data that appears within the map view. As this example shows on Mapbox-gl-js: https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/?q=geojson%20source&size=n_10_n

From the React-Map-gl's documentation: https://uber.github.io/react-map-gl/docs/api-reference/static-map#getmap It says that you will be able to use queryRenderedFeatures as a method for a static map, but the way I've added it seems wrong... And there are not many resources online :/

Any help would be appreciated! :)

export default function Map() {


  const [data, setData] = useState()
  const [viewport, setViewport] = useState({
    latitude: -28.016666,
    longitude: 153.399994,
    zoom: 12,
    bearing: 0,
    pitch: 0
  })
  const mapRef = useRef()


  useEffect(() => {
    fetch('../data.json')
      .then(res => res.json())
      .then(res => setData(res))
  },[])


  function features () { 
    mapRef.current.queryRenderedFeatures( { layers: ['ramps'] })
  }


  function filterRamps (e) {
    data.features.filter(feature => {
      return feature.properties.material === e.target.value
    })
  }


  const handleClick = () => {
    setData(filterRamps())
  }


  if (!data) {
    return null
  }


  return (
    <div style={{ height: '100%', position: 'relative' }}>
      <MapGL
        ref={mapRef}
        {...viewport}
        width="100%"
        height="100%"
        mapStyle="mapbox://styles/mapbox/dark-v9"
        onViewportChange={setViewport}
        mapboxApiAccessToken={Token}
        queryRenderedFeatures={features}
      >
        <Source type="geojson" data={data}>
          <Layer {...dataLayer} />
        </Source>

      </MapGL>

      <Control
        data={data}
        onClick={handleClick}
      />
    </div>


  )
}
aichichi
  • 35
  • 2
  • 8

1 Answers1

3

You need something like:

...
const mapRef = useRef()

...
<MapGL
    ref={mapRef}
    onClick={e => {
        const features = mapRef.current.queryRenderedFeatures(e.geometry.coordinates, { layers: ['ramps'] })
        console.log(features)
    }}
    ...
/>
greenafrican
  • 2,516
  • 5
  • 27
  • 38