Snappy and satisfying tools that just work

Animating dashed line paths in Mapbox and Maplibre

A flexible algorithm to animate ant-path lines in any shape you like.

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: 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
    }

    animationFrame = requestAnimationFrame(animateDashArray)
  }

  // start the animation
  animateDashArray(0)
}

// usage
animateAntPath(mapInstance, "line-layer-id", { speed: 0, dash: 1, gap: 1 })

This tool was developed by Brody Smith.

Say thanks