Middle+
Case: it is necessary to implement smooth animation of a car on the map. Telemetry (latitude, longitude, angle) comes twice a second, the car jumps between coordinates. How would you implement this?
sobes.tech AI
Answer from AI
For smooth animation of a vehicle on the map when updating telemetry twice a second, interpolation between the received coordinates and angles can be used.
Main idea:
- When new data (latitude, longitude, angle) is received, save the current and new values.
- Start an animation that smoothly changes the vehicle's position and angle from the current values to the new ones over a period of time, for example, 500 ms (since data arrives every 500 ms).
- Linear interpolation (LERP) can be used for coordinates and angles.
- The animation can be implemented using
requestAnimationFramefor smoothness.
Example in JavaScript (using Leaflet or a similar library):
let currentPos = {lat: 0, lng: 0, angle: 0};
let targetPos = {lat: 0, lng: 0, angle: 0};
let animationStart = null;
const animationDuration = 500; // ms
function lerp(start, end, t) {
return start + (end - start) * t;
}
function animate(timestamp) {
if (!animationStart) animationStart = timestamp;
const progress = Math.min((timestamp - animationStart) / animationDuration, 1);
const lat = lerp(currentPos.lat, targetPos.lat, progress);
const lng = lerp(currentPos.lng, targetPos.lng, progress);
const angle = lerp(currentPos.angle, targetPos.angle, progress);
// Update vehicle position and angle on the map
updateCarOnMap(lat, lng, angle);
if (progress < 1) {
requestAnimationFrame(animate);
} else {
currentPos = {...targetPos};
animationStart = null;
}
}
function onTelemetryReceived(newLat, newLng, newAngle) {
targetPos = {lat: newLat, lng: newLng, angle: newAngle};
animationStart = null;
requestAnimationFrame(animate);
}
Thus, between coordinate updates, the vehicle will smoothly move and turn, avoiding 'jumps'.