我正在使用ArcGIS API for JavaScript来显示地图,并且我想在有人点击地图时获取所选要素。这是我的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>
</>
)
}
我在
useEffect
中初始化了地图,并使用useState
保存了地图视图。根据文档,你需要在另一个useEffect
中添加事件处理程序,我尝试过这样做,但是当我点击地图时,handleClick
函数没有运行。
view
为空,则直接返回,而不继续执行下一行代码。 - Mark Schultheissif (!view) return;
- Mark Schultheissif (!view) return;
- undefinedhandleClick
函数却没有运行。 - Luis Carlos Cruz CastillohandleClick
函数却没有运行。 - Luis Carlos Cruz Castillo