Animate a line
Animate a line by updating a GeoJSON source on each frame. See the example: https://docs.mapbox.com//mapbox-gl-js/example/animate-a-line/
by Amatewasu
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css">
<div id="map"></div>
<button id="pause"></button>
CSS
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
button {
position: absolute;
margin: 20px;
}
#pause::after {
content: 'Pause';
}
#pause.pause::after {
content: 'Play';
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1IjoiYW1hdGV3YXN1IiwiYSI6ImNrYXV2ZTlqYTB6YjQyeWwyYXZvZTZ3cWYifQ.WCLjyDZ7Bn9bLM1E2BzQcw';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [0, 0],
zoom: 0.5
});
// Create a GeoJSON source with an empty lineString.
var geojson = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': [[0, 0]]
}
}
]
};
var speedFactor = 30; // number of frames per longitude degree
var animation; // to store and cancel the animation
var startTime = 0;
var progress = 0; // progress = timestamp - startTime
var resetTime = false; // indicator of whether time reset is needed for the animation
var pauseButton = document.getElementById('pause');
map.on('load', function () {
map.addSource('line', {
'type': 'geojson',
'data': geojson
});
// add the line which will be modified in the animation
map.addLayer({
'id': 'line-animation',
'type': 'line',
'source': 'line',
'layout': {
'line-cap': 'round',
'line-join': 'round'
},
'paint': {
'line-color': '#ed6498',
'line-width': 5,
'line-opacity': 0.8
}
});
startTime = performance.now();
animateLine();
// click the button to pause or play
pauseButton.addEventListener('click', function () {
pauseButton.classList.toggle('pause');
if (pauseButton.classList.contains('pause')) {
cancelAnimationFrame(animation);
} else {
resetTime = true;
animateLine();
...