Skip to content

Instantly share code, notes, and snippets.

@twelch
Last active June 25, 2020 21:54
Show Gist options
  • Save twelch/18d53240f638d0c77cd4 to your computer and use it in GitHub Desktop.
Save twelch/18d53240f638d0c77cd4 to your computer and use it in GitHub Desktop.
Animating point along a line with turf-along
license: mit

Animates using distance along line allowing for animation speed control.

Built with blockbuilder.org

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.12.0/mapbox-gl.js'></script>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/turf/v2.0.2/turf.min.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.12.0/mapbox-gl.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>
mapboxgl.accessToken = 'pk.eyJ1IjoidHdlbGNoIiwiYSI6Il9pX3dtb3cifQ.YcYnsO0X2p3x0HpHPFfleg';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v8',
center: [-122.580067, 45.548602],
zoom: 20
});
var iPath = turf.linestring([
[ -122.579915799999981, 45.5485545, 0.0 ], [ -122.57994530000002, 45.5485536, 0.0 ], [ -122.579944, 45.5485996, 0.0 ], [ -122.580011, 45.54860810000001, 0.0 ], [ -122.5799507, 45.5486043, 0.0 ], [ -122.579954700000016, 45.5485489, 0.0 ], [ -122.579903799999983, 45.5485489, 0.0 ]
]);
var iPathLength = turf.lineDistance(iPath, 'miles');
var iPoint = turf.along(iPath, 0, 'miles');
map.on('style.load', function () {
map.addSource("path", {
"type": "geojson",
"data": iPath,
"maxzoom": 20
});
map.addLayer({
"id": "path",
"type": "line",
"source": "path",
"layout": {
"line-join": "round",
"line-cap": "round"
},
"paint": {
"line-color": "#888",
"line-width": 2
}
});
map.addSource("peep", {
"type": "geojson",
"data": iPoint,
"maxzoom": 20
});
map.addLayer({
"id": "peep",
"type": "circle",
"source": "peep",
"layout": {},
"paint": {
"circle-radius": 4
}
});
var step = 0;
var numSteps = 500; //Change this to set animation resolution
var timePerStep = 20; //Change this to alter animation speed
var pSource = map.getSource('peep');
var interval = setInterval(function() {
step += 1;
if (step > numSteps) {
clearInterval(interval);
} else {
var curDistance = step / numSteps * iPathLength;
var iPoint = turf.along(iPath, curDistance, 'miles');
pSource.setData(iPoint);
console.log(curDistance);
}
}, timePerStep);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment