Move Marker Along Line

Simple marker animation
Select all
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Move Marker Along Line</title>
  
  <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
  <script src='//api.tiles.mapbox.com/mapbox.js/v1.5.0/mapbox.js'></script>
  <link href='//api.tiles.mapbox.com/mapbox.js/v1.5.0/mapbox.css' rel='stylesheet' />
  
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
  </style>
</head>
<body>
<div id='map'></div>
<script>
var map = L.mapbox.map('map', 'examples.map-20v6611k')
    .setView([0, 0], 1);

// Generate a GeoJSON line: you can load GeoJSON via AJAX, or
// generate it some other way
var geojson = { type: 'LineString', coordinates: [] },
    start = [10, 20],
    momentum = [3, 3];
for (var i = 0; i < 300; i++) {
    start[0] += momentum[0];
    start[1] += momentum[1];
    if (start[1] > 60 || start[1] < -60) momentum[1] *= -1;
    if (start[0] > 170 || start[0] < -170) momentum[0] *= -1;
    geojson.coordinates.push(start.slice());
}

var geojsonLayer = L.geoJson(geojson).addTo(map),
    marker = L.marker([0, 0], {
        icon: L.mapbox.marker.icon()
    }).addTo(map),
    j = 0;

tick();
function tick() {
    // set the marker to be at the same point as one of the segments
    // of the line
    marker.setLatLng(L.latLng(
        geojson.coordinates[j][1],
        geojson.coordinates[j][0]));

    // move to the next point in the line or loop to the first point if
    // j runs off the end of the array
    if (++j < geojson.coordinates.length) setTimeout(tick, 100);
}
</script>
The code and documentation to mapbox.js is hosted on GitHub where you can contribute changes and improvements.