我如何将 SnakeAnim 与 react-leaflet 一起使用

How can I use SnakeAnim with react-leaflet

我想使用 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);
    });
  }, [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='&amp;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 添加一个侦听器并通过标志触发动画。

Demo