Fit a Map to a Bounding Box
map.fitBounds in Maptoolkit Maps JS adjusts the center and zoom level so a given LngLatBounds fits within the map container, with optional padding to keep content clear of the edges. You can pass padding as a single number or as an object with top, bottom, left, and right values to accommodate overlapping UI elements. Use this whenever you need to show a specific region on load, after a search result, or when navigating to a selected area.
const API_KEY = 'YOUR_API_KEY';
const map = new maptoolkit.Map({
container: 'map',
apiKey: API_KEY,
style: `https://styles.maptoolkit.net/maptoolkit/maptoolkit.summer.json?api_key=${API_KEY}`,
center: [13.0, 47.5],
zoom: 5,
attributionControl: { compact: false }
});
map.addControl(new maptoolkit.NavigationControl(), 'top-right');
document.getElementById('fit').addEventListener('click', () => {
// Bounding box covering Austria
map.fitBounds([[9.5, 46.4], [17.2, 49.1]], { padding: 40 });
});<!DOCTYPE html>
<html lang="en">
<head>
<title>Fit a Map to a Bounding Box - Maptoolkit Maps JS</title>
<meta property="og:description" content="Fit the map view to a geographic bounding box with padding." />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/@maptoolkit/[email protected]/dist/maptoolkit.js"></script>
<link rel="stylesheet" href="https://unpkg.com/@maptoolkit/[email protected]/dist/maptoolkit.css" />
<style>
html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
#map { width: 100%; height: 100%; }
#fit {
position: absolute;
top: 10px;
left: 10px;
padding: 10px 20px;
background: #ee8a65;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
font-size: 14px;
}
</style>
</head>
<body>
<div id="map"></div>
<button id="fit">Fit to Austria</button>
<script>
const API_KEY = 'YOUR_API_KEY';
const map = new maptoolkit.Map({
container: 'map',
apiKey: API_KEY,
style: `https://styles.maptoolkit.net/maptoolkit/maptoolkit.summer.json?api_key=${API_KEY}`,
center: [13.0, 47.5],
zoom: 5,
attributionControl: { compact: false }
});
map.addControl(new maptoolkit.NavigationControl(), 'top-right');
document.getElementById('fit').addEventListener('click', () => {
// Bounding box covering Austria
map.fitBounds([[9.5, 46.4], [17.2, 49.1]], { padding: 40 });
});
</script>
</body>
</html>Use the prompt below with any LLM to get the same result. Make sure the Maptoolkit MCP server is connected first — check out AI Integration & MCP to get started.
Use the Maptoolkit Connector. Create an interactive map with zoom level 5, centered around [13.0, 47.5]. Add a button that fits the map view to Austria’s bounding box.