Skip to main content

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>
<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="" rel="stylesheet">
<script src=""></script>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
#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;
<div id="map"></div>
<button id="fit">Fit to Kenya</button>
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', () => {
[32.958984, -5.353521], // southwestern corner of the bounds
[43.50585, 5.615985] // northeastern corner of the bounds

Was this example helpful?