Fit a map to a bounding box
Use fitBounds to show a specific area of the map in view, regardless of the pixel size of the map.
NPM module setup
npm install --save @maptiler/sdk
import { Map, MapStyle, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
config.apiKey = 'YOUR_MAPTILER_API_KEY_HERE';
const map = new Map({
container: 'map',
style: MapStyle.STREETS,
center: [-74.5, 40],
zoom: 9
});
document.getElementById('fit').addEventListener('click', function () {
map.fitBounds([
[32.958984, -5.353521],
[43.50585, 5.615985]
]);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Fit a map to a bounding box | NPM example</title>
<link rel="stylesheet" href="./style.css">
</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 type="module" src="./main.js"></script>
</body>
</html>
body {margin: 0; padding: 0;}
#map {position: absolute; top: 0; bottom: 0; width: 100%;}
Related examples
Center map by visitor’s country IP
TutorialsThis tutorial shows how to center map based on the visitor’s country bounds using the MapTiler Geolocation API.