Fit a map to a bounding box
This example zooms and pans the map so the new visible area of the map fits within the specified geographical bounds.
It uses the JavaScript addEventListener
method to attach a click listener to the 'Fit to Kenya' button so that when a user clicks the button, fitBounds()
pans and zooms the map viewport from the starting location on the city of Mombasa so that the new visible area includes the entire country of Kenya.
The fitBounds()
method accepts a geographic bounding box representing the southwest and northeast corners of the area you would like to fit the map's viewport to. The coordinates must be passed in as a LngLatBoundsLike
(A LngLatBounds
object, an array of LngLatLike
objects in [sw, ne]
order, or an array of numbers in [west, south, east, north]
order). Longitude
values in LngLatBoundsLike
are typically set between -180
to 180
, but can exceed this range if necessary. Latitude
values must be within -90
to 90
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fit a map to a bounding box</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>
#fit {
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="fit">Fit to Kenya</button>
<script>
// TO MAKE THE MAP APPEAR YOU MUST
// ADD YOUR ACCESS TOKEN FROM
// https://account.mapbox.com
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN';
const map = new mapboxgl.Map({
container: 'map', // container ID
// Choose from Mapbox's core styles, or make your own style with Mapbox Studio
style: 'mapbox://styles/mapbox/streets-v12', // style URL
center: [39.657325, -4.024902], // starting position ([lng, lat] for Mombasa, Kenya)
zoom: 9 // starting zoom
});
/*
* When a user clicks the button, `fitBounds()` zooms and pans
* the viewport to contain a bounding box that surrounds Kenya.
* The [lng, lat] pairs are the southwestern and northeastern
* corners of the specified geographical bounds.
*/
document.getElementById('fit').addEventListener('click', () => {
map.fitBounds([
[32.958984, -5.353521], // [lng, lat] - southwestern corner of the bounds
[43.50585, 5.615985] // [lng, lat] - northeastern corner of the bounds
]);
});
</script>
</body>
</html>
YOUR_MAPBOX_ACCESS_TOKEN
with an access token from your Mapbox account.