Animating dashed line paths in Mapbox and Maplibre
A flexible algorithm to animate an ant-path line in Mapbox or Maplibre.
Mapbox ant-path line animation
Loading map ...
Below is the algorithm used here, which takes any speed and dash/gap size and starts an animation loop. Be sure to set lineMetrics: true on your line layer in Mapbox/MapLibre.
ts
type AntPathOptions = {
speed?: number
dash?: number
gap?: number
}
const animateAntPath = (
map,
layerId: string,
options: AntPathOptions = {}
) => {
const { speed = 0, dash = 1, gap = 1 } = options
const precision = 1 / 120
let dashArraySequence: number[][] = []
let step = 1
let interval = Math.min(25, Math.abs(100 / (speed * (dash + gap))))
for (let i = 0; i <= dash; i += precision)
dashArraySequence.push([i, gap, dash - i])
for (let i = precision; i <= gap; i += precision)
dashArraySequence.push([0, i, dash, gap - i])
if (speed < 0) dashArraySequence.reverse()
function animateDashArray(timestamp: number): void {
const newStep = Math.floor(
(timestamp / interval) % dashArraySequence.length
)
if (newStep !== step) {
map.setPaintProperty(
layerId,
"line-dasharray",
dashArraySequence[newStep]
)
step = newStep
}
// Request the next frame of the animation.
animationFrame = requestAnimationFrame(animateDashArray)
}
// start the animation
animateDashArray(0)
}