I'm using the ArcGIS API for JavaScript to display a map and I want to get the selected feature when someone clicks on the map. This is my MapComponent
export const MapComponent = () => {
const elementRef = useRef(null);
const [view, setView] = useState<MapView>();
const [selected, setSelected] = useState<Feature>();
const handleClick = useCallback((e: any) => {
if (!view) return;
view.hitTest(e)
.then(res => {
if (res.results.length > 0) {
const feature = res.results[0];
if (feature.type === 'graphic') {
setSelected(feature.graphic.attributes)
}
}
})
}, [view]);
useEffect(() => {
if (!view) return;
const handle = view.on('click', handleClick)
return handle && handle.remove();
}, [view]);
useEffect(() => {
const loadMap = async () => {
const { init } = await import('./Map');
const mapView = init(elementRef.current);
setView(mapView);
}
loadMap()
return () => view && view.destroy();
}, []);
return (
<>
<div
ref={elementRef}
style={{ height: '500px', width: '800px' }}
>
</div>
<pre>{JSON.stringify(selected, null, 2)}</pre>
</>
)
}
I initialized the map in a useEffect
and save the map view with useState
, I saw in the documentation you have to add your event handlers on another useEffect
and I tried to do that, but the function handleClick
doesn't run when I click on the map
if (!view) return;
– BradburyhandleClick
does not run when I click on the map – Kaohsiung