All docsNMaps GL JS DocsExamplesFit a map to a bounding box

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.

<!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" />
<script src="https://cdn.ndrive.com/nmapsgl/v1.6.6/nmaps-gl.js"></script>
<link href="https://cdn.ndrive.com/nmapsgl/v1.6.6/nmaps-gl.css" rel="stylesheet" />
<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
nmapsgl.accessToken = '<your access token here>';
const map = new nmapsgl.Map({
container: 'map',
style: 'Streets',
center: [-74.5, 40],
zoom: 9
});
document.getElementById('fit').addEventListener('click', () => {
map.fitBounds([
[32.958984, -5.353521],
[43.50585, 5.615985]
]);
});
</script>
</body>
</html>