Leaflet在Ionic React中点击GeoJSON图层切换颜色仅生效一次问题
问题根因
你的代码问题出在事件绑定的时机错误:onEachFeature 仅会在GeoJSON图层初始化、每个要素首次加载时执行一次。你在这个阶段根据初始颜色绑定了固定逻辑的点击事件,绑定完成后判断颜色的逻辑不会再次执行,因此第一次点击修改颜色后,后续点击触发的始终是初始化时绑定的固定逻辑,无法实现来回切换。
修复方案
调整事件绑定逻辑:仅在onEachFeature中绑定一次点击事件,把颜色切换的判断逻辑放在点击事件的回调内部,保证每次点击都会重新判断当前颜色并切换。
修改后的代码如下:
function LeafletMap() { const [map, setMap] = useState(null) const onEachClick = (info, layer) => { const part = info.properties.Objekt_ID const id = info.properties.FID_ layer.bindPopup("Object ID: <b>" + part + "</b><br>FID: <b>" + id + "</b>") // 仅绑定一次点击事件,切换逻辑放在回调内每次点击都执行 layer.on('click', (event) => { const currentLayer = event.target const newColor = currentLayer.options.color === 'blue' ? 'red' : 'blue' currentLayer.setStyle({ color: newColor }) }) } const displayMap = useMemo( () => ( <MapContainer center={center} zoom={zoom} scrollWheelZoom={false} whenCreated={setMap}> <LayersControl position="topright"> <LayersControl.BaseLayer checked name="OpenStreetMap - Map"> <TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png" /> </LayersControl.BaseLayer> <LayersControl.BaseLayer name="Esri - Satelite"> <TileLayer attribution='Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}" /> </LayersControl.BaseLayer> </LayersControl> <GeoJSON data={PL.features} onEachFeature={onEachClick} color="blue"/> <GeoJSON data={WWD.features} onEachFeature={onEachClick} color="blue"/> </MapContainer> ), [], ) window.dispatchEvent(new Event('resize')); return ( <div> {displayMap} </div> ) } export default LeafletMap
内容的提问来源于stack exchange,提问作者jonsken
相关产品推荐
相关产品推荐

