Mapbox-gl ant path
ant path with mapbox-gl
by cs09g
HTML
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.5.0/mapbox-gl.css">
<div id="map"></div>
<div class="buttons">
<button id="start">start</button><button id="stop">stop</button>
</div>
CSS
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.buttons {
position: absolute;
}
JavaScript
mapboxgl.accessToken = 'pk.eyJ1IjoiZmFyYWRheTIiLCJhIjoiTUVHbDl5OCJ9.buFaqIdaIM3iXr1BOYKpsQ';
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-122.486052, 37.830348],
zoom: 15
});
// https://gist.github.com/cs09g/8d3ca19009c79e473f8b57f62f6e7367
let dash = [3, 3]; // your input; dash you want to animate
let speed = 0.5;
let dashArraySeq = createDashArraySeq(dash, speed); // `dashArraySeq` contains dash arrays you can use
function createDashArraySeq(dash, speed = 1) {
let dashArraySeq = [dash];
for (let i = speed, len = dash[0] + dash[1]; i < len; i += speed) {
const arr = [];
if (i <= len - dash[0]) {
arr.push(0, i, dash[0], dash[1] - i);
} else {
const leftFillCnt = i - (len - dash[0]);
arr.push(leftFillCnt, dash[1], dash[0] - leftFillCnt, 0);
}
dashArraySeq.push(arr);
}
return dashArraySeq;
}
let dashArrayIdx = 0;
let raf;
function animateLine(ts) {
dashArrayIdx = (dashArrayIdx + 1) % dashArraySeq.length;
map.setPaintProperty('route', 'line-dasharray', dashArraySeq[dashArrayIdx]);
raf = requestAnimationFrame(animateLine);
}
document.querySelector("#start").addEventListener("click", () => {
if (!raf) {
raf = requestAnimationFrame(animateLine);
}
});
document.querySelector("#stop").addEventListener("click", () => {
cancelAnimationFrame(raf);
raf = null;
});
map.on('load', function() {
map.addLayer({
"id": "route",
"type": "line",
"source": {
"type": "geojson",
"data": {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-122.48369693756104, 37.83381888486939],
[-122.48348236083984, 37.83317489144141],
[-122.48339653015138, 37.83270036637107],
[-122.48356819152832, 37.832056363179625],
[-122.48404026031496, 37.83114119107971],
[-122.48404026031496,...