使用React Leaflet我可以很高兴地获得一个LayerControl,通过它我可以启用/禁用Leaflet Marker LayerGroups,但无法理解如何以编程方式进行此操作。
Leaflet documentation提出以下建议:
var layer = L.marker(latlng).addTo(map);
layer.addTo(map);
layer.remove();
[同样,this Leaflet issue建议您跟踪自己的图层。但是如何在React-Leaflet中做到这一点?感觉好像已被抽象得太多了。
我简化了React Leaflets的example/components/layers-control.js以找出问题,但无法理解任何要素:
class App extends Component {
render() {
return (
<div className='map'>
<Map className='map' center={[51,0]} zoom={10} id='map1'>
<LayersControl position="topright" id="lc1">
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
id="tl1"
/>
<Overlay name="Layer 1" id="l1">
<LayerGroup id="lg1">
<Marker position={[51, 0.1]}></Marker>
</LayerGroup>
</Overlay>
<Overlay name="Layer 2">
<LayerGroup>
<Marker position={[51, 0.2]}></Marker>
</LayerGroup>
</Overlay>
</LayersControl>
</Map>
</div>
);
}
}
您可以使用ref分别保留地图实例和叠加层实例的区域,然后使用一些原始的传单代码,就像没有React一样,可以实现这一点:
const mapRef = useRef();
const firstOverlayRef = useRef();
const secondOverlayRef = useRef();
const addLayers = () => {
if (mapRef.current && firstOverlayRef.current) {
const map = mapRef.current.leafletElement;
const firstLayer = firstOverlayRef.current.leafletElement;
const secondLayer = secondOverlayRef.current.leafletElement;
[firstLayer, secondLayer].forEach(layer => map.addLayer(layer));
}
};
const removeLayers = () => {
if (mapRef.current && firstOverlayRef.current) {
const map = mapRef.current.leafletElement;
const firstLayer = firstOverlayRef.current.leafletElement;
const secondLayer = secondOverlayRef.current.leafletElement;
[firstLayer, secondLayer].forEach(layer => map.removeLayer(layer));
}
};
....
<Map center={center} zoom={10} style={{ height: "90vh" }} ref={mapRef}>
<LayersControl position="topright">
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
id="tl1"
/>
<Overlay name="Layer 1">
<LayerGroup id="lg1" ref={firstOverlayRef}>
<Marker position={[51, 0.1]} icon={icon} />
</LayerGroup>
</Overlay>
<Overlay name="Layer 2">
<LayerGroup ref={secondOverlayRef}>
<Marker position={[51, 0.2]} icon={icon} />
</LayerGroup>
</Overlay>
</LayersControl>
</Map>
<button onClick={addLayers}>Add Layers</button>
<button onClick={removeLayers}>Remove layers</button>
</>