【问题标题】:How can I use SnakeAnim with react-leaflet如何将 SnakeAnim 与 react-leaflet 一起使用
【发布时间】:2020-09-24 04:11:09
【问题描述】:

我想使用 Leaflet.Polyline.SnakeAnim 并且我有一个问题。是否有一个如何在 react-leaflet 中创建自定义组件的示例?

【问题讨论】:

    标签: javascript reactjs leaflet react-leaflet


    【解决方案1】:

    安装库并导入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 wrapper 中导入 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>
        </>
      );
    

    创建一个 btn 添加一个监听器并通过一个标志触发动画。

    Demo

    【讨论】:

    • 哦,非常感谢你,也许你能告诉我如何从坐标数组中渲染 L.featureGroup。它是如此复杂:
    • 请为此创建另一个问题,因为这是一个不同的问题。
    • 我明白了,我只是创建了另一个问题,这里是链接link 你能帮我吗:
    • 请阅读this,了解如何提出问题并提供重现问题所需的所有必要细节。提供坐标数组和其他需要的东西。要具体,以便人们可以帮助您。
    • 很抱歉,这是我第一次使用stackoverflow,我已经解决了这个问题。
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2018-12-30
    相关资源
    最近更新 更多