首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React中使用Leaflet.Polyline.SnakeAnim插件而不使用react-leaflet?

如何在React中使用Leaflet.Polyline.SnakeAnim插件而不使用react-leaflet?
EN

Stack Overflow用户
提问于 2020-06-12 18:46:17
回答 1查看 341关注 0票数 0

我正在React项目中使用Leaflet,我想导入一个插件来扩展Leaflet Polyline,该插件是Leaflet.Polyline.SnakeAnim

我没有使用react-leaflet,而是直接使用Javascript库,以下是我的代码:

代码语言:javascript
复制
import React from 'react';
import L from 'leaflet';
import 'leaflet.polyline.snakeanim';

class LeafletMap extends React.Component {

  componentDidMount() {

    this.map = L.map('leafletMap', {
      center:[0,0], 
      zoom: 2
    });

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.map);

    let polylinePoints = [
      [57.74, 11.94],
      [0,0],
      [22,22]
    ];

    L.polyline(polylinePoints, {
      color: 'blue',
      weight: 8
    }).addTo(this.map).snakeIn();

   }
}

在我的集成开发环境中,我在snakeIn()上收到一个警告,说函数未解决。而且这个插件根本不起作用。

如何正确地将传单插件导入React?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-12 21:45:15

如果要在贴图加载时触发动画,则将蛇逻辑放置在componentDidMount中,否则在贴图加载时保存mapInstance,然后使用按钮在componentDidUpdate中触发蛇动画。

代码语言:javascript
复制
class LeafletMap extends React.Component {
  state = {
    mapInstance: null,
    startAnimation: false
  };

  startSnake = () => this.setState({ startAnimation: true });

  componentDidMount() {
    const map = L.map("map").setView([51.505, -0.09], 13);

    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    this.setState({ mapInstance: map });
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.startAnimation !== this.state.startAnimation) {
      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 })
      ]);

      this.state.mapInstance.fitBounds(route.getBounds());

      this.state.mapInstance.addLayer(route);

      route.snakeIn();

      route.on("snakestart snake snakeend", ev => {
        console.log(ev.type);
      });
    }
  }

  render() {
    return (
      <>
        <div id="map" style={{ height: "90vh" }} />
        <button onClick={this.startSnake}>Snake it!</button>
      </>
    );
  }
}

Demo

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62342633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档