Add custom zoom control
The custom zoom control in this example shows the exact current zoom level on a map. It helps set up zoom-based style rules or understand data resolution.
Adding custom controls can make your application stand out. Before you start making your controls, check out the premade MapTiler SDK controls (Geolocate, Scale, terrain, …).
NPM module setup
npm install --save @maptiler/sdk
import { Map, config } from '@maptiler/sdk';
import '@maptiler/sdk/dist/maptiler-sdk.css';
// Initialize MapTiler SDK
config.apiKey = "YOUR_MAPTILER_API_KEY_HERE";
// Initialize the map
const map = new Map({
container: 'map', // The ID of the HTML element where the map will be rendered
});
// --- Custom Map Control Implementation ---
// This class will define how your custom control behaves and looks
// Read more about Icontrol https://docs.maptiler.com/sdk-js/api/controls/#icontrol
class ZoomControl {
onAdd(map) {
this._map = map;
this._container = document.createElement('div'); // Create a new div element
this._container.className = 'maplibregl-ctrl custom-map-control'; // Add SDK's control class and your custom class
this._updateZoomHandler = () => {
this._container.innerHTML = `${map.getZoom().toFixed(2)}`;
};
// Initial text with current zoom
this._updateZoomHandler();
// Add event listener for zoom changes
map.on('zoomend', this._updateZoomHandler);
return this._container;
}
onRemove() {
this._container.parentNode.removeChild(this._container);
this._map = undefined;
}
}
map.addControl(new ZoomControl(), 'top-right');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Add custom zoom control | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
/* Custom control styling */
.custom-map-control {
background-color: rgba(255, 255, 255, 1);
border-radius: 3px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
font-weight: bold;
width: 33px;
height: 33px;
font-size: 10px;
color: #333;
display: flex;
justify-content: center;
/* Centers items horizontally */
align-items: center;
/* Ensure it's above the map but part of the map's control flow */
z-index: 1;
pointer-events: auto;
/* Allow interaction with the control */
}
Related examples
Custom control programmatically
ExamplesProgrammatically add custom controls for dynamic map logic integration.