简体   繁体   中英

How can I use SnakeAnim with react-leaflet

I would like to use Leaflet.Polyline.SnakeAnim and I have a question. Is there an example how to create custom component in react-leaflet?

Install the library and import leaflet.polyline.snakeanim/L.Polyline.SnakeAnim.js

then create a wrapper to call the necessary methods to trigger the animation. You can have a startAnimation prop to trigger the animation but you can adjust it to your needs:

... // 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;
};

Use it like this, import the wrapper inside react-leaflet's Map wrapper:

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>
    </>
  );

Create a btn add a listener and trigger the animation via a flag.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM