Skip to main content

Slowly fly to a location

This example uses flyTo with flyOptions to slowly zoom to a location, and creates a custom atmosphere effect using setFog.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Slowly fly to a location</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v3.8.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.8.0/mapbox-gl.js"></script>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<style>
#fly {
display: block;
position: relative;
margin: 0px auto;
width: 50%;
height: 40px;
padding: 10px;
border: none;
border-radius: 3px;
font-size: 12px;
text-align: center;
color: #fff;
background: #ee8a65;
}
</style>
<div id="map"></div>
<br>
<button id="fly">Fly</button>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';
// These options control the camera position after animation
const start = {
center: [80, 36],
zoom: 1,
pitch: 0,
bearing: 0
};
const end = {
center: [8.11862, 46.58842],
zoom: 12.5,
bearing: 130,
pitch: 75
};
const map = new mapboxgl.Map({
container: 'map',
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/satellite-streets-v12',
...start
});

map.on('style.load', () => {
// Custom atmosphere styling
map.setFog({
'color': 'rgb(220, 159, 159)', // Pink fog / lower atmosphere
'high-color': 'rgb(36, 92, 223)', // Blue sky / upper atmosphere
'horizon-blend': 0.4 // Exaggerate atmosphere (default is .1)
});

map.addSource('mapbox-dem', {
'type': 'raster-dem',
'url': 'mapbox://mapbox.terrain-rgb'
});

map.setTerrain({
'source': 'mapbox-dem',
'exaggeration': 1.5
});
});

let isAtStart = true;

document.getElementById('fly').addEventListener('click', () => {
// depending on whether we're currently at point a or b,
// aim for point a or b
const target = isAtStart ? end : start;
isAtStart = !isAtStart;

map.flyTo({
...target, // Fly to the selected target
duration: 12000, // Animate over 12 seconds
essential: true // This animation is considered essential with
//respect to prefers-reduced-motion
});
});
</script>

</body>
</html>
This code snippet will not work as expected until you replace YOUR_MAPBOX_ACCESS_TOKEN with an access token from your Mapbox account.
Was this example helpful?