Skip to content

Instantly share code, notes, and snippets.

@mdamien
Last active October 6, 2016 13:30
Show Gist options
  • Save mdamien/db1dd304baa035c517f19b193a518dda to your computer and use it in GitHub Desktop.
Save mdamien/db1dd304baa035c517f19b193a518dda to your computer and use it in GitHub Desktop.
mapbox keys control
<!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.25.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.25.1/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.eyJ1IjoicG93ZXJzaG9wcyIsImEiOiJhYUdRR0t3In0.oTz8RJqED2YEcDRfJYNAOQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-streets-v9',
center: [-87.6298, 41.8781],
zoom: 14,
bearing: -12,
pitch: 60,
interactive: false
});
// pixels the map pans each second a key is pressed
var DELTA_DISTANCE = 1000;
// degrees the map rotates each second a key is pressed
var DELTA_DEGREES = 250;
function easing(t) {
return t * (2 - t);
}
var keysDown = {};
var lastUpdate = undefined;
function move() {
var now = new Date().getTime();
var dt = (now - (lastUpdate || now)) / 1000;
var deltaDistance = DELTA_DISTANCE * dt;
var deltaDegrees = DELTA_DEGREES * dt;
var newBearing = map.getBearing();
var offsetY = 0;
if (keysDown[38]) { // up
offsetY += deltaDistance;
}
if (keysDown[40]) { // down
offsetY -= deltaDistance;
}
if (keysDown[37]) { // left
newBearing -= deltaDegrees
}
if (keysDown[39]) { // right
newBearing += deltaDegrees;
}
map.easeTo({
bearing: newBearing,
center: map.getCenter(),
offset: [0, offsetY],
easing: easing,
});
lastUpdate = now;
requestAnimationFrame(move);
}
map.on('load', function() {
map.getCanvas().focus();
map.getCanvas().addEventListener('keydown', function(e) {
e.preventDefault();
keysDown[e.which] = true;
}, true);
map.getCanvas().addEventListener('keyup', function(e) {
e.preventDefault();
if (keysDown[e.which]) {
delete keysDown[e.which];
}
}, true);
map.getCanvas().addEventListener('blur', function(e) {
keysDown = {};
});
requestAnimationFrame(move);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment