我正在React项目中使用Leaflet,我想导入一个插件来扩展Leaflet Polyline,该插件是Leaflet.Polyline.SnakeAnim
我没有使用react-leaflet,而是直接使用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?
发布于 2020-06-12 21:45:15
如果要在贴图加载时触发动画,则将蛇逻辑放置在componentDidMount中,否则在贴图加载时保存mapInstance,然后使用按钮在componentDidUpdate中触发蛇动画。
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:
'© <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>
</>
);
}
}https://stackoverflow.com/questions/62342633
复制相似问题