Within my reactjs app, I'm using a light-weight map library called pidegon-maps to display vessel locations. Without trying to use the bigger libraries (leaflet, Google Maps react), I'm trying to animate the route a vessel takes.
Taking inspiration from this question, I tried to create a similar implementation.
useEffect(() => {
let start = [0.108266, 52.202758];
let end = [0.11556, 52.201733];
const speedFactor = 500;
let diffX = parseFloat(end[0]) - parseFloat(start[0]);
let diffY = parseFloat(end[1]) - parseFloat(start[1]);
let sfX = diffX / speedFactor;
let sfY = diffY / speedFactor;
let i = 0;
let j = 0;
let lineCoordinates = [];
while (i < diffX || Math.abs(j) < Math.abs(diffY)) {
lineCoordinates.push([start[0] + i, start[0] + j]);
if (i < diffX) {
i += sfX;
}
if (Math.abs(j) < Math.abs(diffY)) {
j += sfY;
}
}
console.log(lineCoordinates);
let animationCounter = 0;
const animateLine = () => {
if (animationCounter < lineCoordinates.length) {
geojson.features[0].geometry.coordinates.push(lineCoordinates[animationCounter]);
requestAnimationFrame(animateLine);
animationCounter++;
}
}
animateLine();
}, []);
For some reason, it runs through the animation really fast, then disappears. It also only shows the line as straight (north and south, no angle at all), so it doesn't actually connect. Distance is correct, but not angle. I tried moving it to state instead, bc when zooming in and out, it causes the map to re-render. This worked okay, but it only animates when zooming in and out. So I can slow it down to 1000 speed factor and zoom in and out and watch it animate, but it won't do it by itself.
Currently, it's in a useEffect, but I also removed it and tried without as well.
There are two ways to achieve this, one is growing the
lineStringby modifying the coordinates like what you are trying to implement.Another method is to use CSS to have the svg draw itself, which is way easier and recommended. The key CSS property
stroke-dashoffsetis now widely supported by modern browsers.Method 1: Use a line with two points with CSS
Sandbox Demo
Note: Don't forget to specify the path length for the SVG as shown below.
Method 2: Your original method with multiple points in the
LineStringI'm not sure what problem your code has since only the
useEffectmethod is shown. However, there are some potential problems:[lng,lat]) are opposite with pigeon-maps coordinates ([lat,lng])requestAnimationFrameframe is used here and if it's used correctly. Hence, I've switched tosetIntervals.lineStringif it is a straight line.The modified code is shown as below: