我对React和JavaScript还很陌生,正在尝试使用React Map gl为我的React Hooks项目编写queryRenderedFeatures过滤器。
该项目有一个庞大的数据列表,我想做的只是过滤地图视图中出现的数据。如Mapbox gl-js上的示例所示:https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/?q=geojson%20source&大小=n_10_n
根据React Map gl的文档:https://uber.github.io/react-map-gl/docs/api-reference/static-map#getmap它说您将能够使用queryRenderedFeatures作为静态映射的方法,但我添加它的方式似乎是错误的。。。在线资源不多:/
如有任何帮助,我们将不胜感激!:(
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>
)
}
您需要类似以下内容:
...
const mapRef = useRef()
...
<MapGL
ref={mapRef}
onClick={e => {
const features = mapRef.current.queryRenderedFeatures(e.geometry.coordinates, { layers: ['ramps'] })
console.log(features)
}}
...
/>