我想使用Leaflet.Polyline.SnakeAnim,我有一个问题。是否有示例如何在react-leaflet中创建自定义组件?
安装库并导入leaflet.polyline.snakeanim/L.Polyline.SnakeAnim.js
然后创建一个包装器,以调用必要的方法来触发动画。您可以使用startAnimation
道具来触发动画,但可以根据需要进行调整:
... // imports here
const SnakeAnim = ({ startAnimation }) => {
const { map } = useLeaflet();
useEffect(() => {
if (!startAnimation) return;
const trd = [63.5, 11];
const mad = [40.5, -3.5];
const lnd = [51.5, -0.5];
const ams = [52.3, 4.75];
const vlc = [39.5, -0.5];
const route = L.featureGroup([
L.marker(trd, { icon }),
L.polyline([trd, ams]),
L.marker(ams, { icon }),
L.polyline([ams, lnd]),
L.marker(lnd, { icon }),
L.polyline([lnd, mad]),
L.marker(mad, { icon }),
L.polyline([mad, vlc]),
L.marker(vlc, { icon })
]);
map.fitBounds(route.getBounds());
map.addLayer(route);
route.snakeIn();
route.on("snakestart snake snakeend", ev => {
console.log(ev.type);
});
console.log(map);
}, [startAnimation]);
return null;
};
像这样使用,将包装器导入react-leaflet的Map包装器中:
const [startAnimation, setStartAnimation] = useState(false);
const startSnake = () => setStartAnimation(true);
return (
<>
<Map center={position} zoom={zoom} style={{ height: "90vh" }}>
<TileLayer
attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<SnakeAnim startAnimation={startAnimation} />
</Map>
<button onClick={startSnake}>Snake it!</button>
</>
);
创建btn添加侦听器并通过标志触发动画。