Restrict Map Panning to an Area
Limit map panning to a specific geographic region using setMaxBounds().
Try panning outside Europe — the map will bounce back to the allowed area.
Set Max Bounds at Initialization
javascript
const map = new mapmetricsgl.Map({
container: 'map',
style: '<StyleFile_URL_with_Token>',
center: [10, 52],
zoom: 3,
maxBounds: [
[-15, 34], // Southwest corner [lng, lat]
[40, 72] // Northeast corner [lng, lat]
]
});Set Max Bounds Dynamically
javascript
// Restrict after initialization
map.setMaxBounds([[-15, 34], [40, 72]]);
// Remove restriction
map.setMaxBounds(null);Also Set Min/Max Zoom
javascript
const map = new mapmetricsgl.Map({
container: 'map',
style: '<StyleFile_URL_with_Token>',
maxBounds: [[-15, 34], [40, 72]],
minZoom: 3, // can't zoom out beyond this
maxZoom: 18 // can't zoom in beyond this
});Complete Example
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link href="https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.css" rel="stylesheet" />
<script src="https://cdn.mapmetrics-atlas.net/versions/latest/mapmetrics-gl.js"></script>
<style>#map { height: 500px; width: 100%; }</style>
</head>
<body>
<div id="map"></div>
<script>
const map = new mapmetricsgl.Map({
container: 'map',
style: '<StyleFile_URL_with_Token>',
center: [10, 52],
zoom: 3,
maxBounds: [[-15, 34], [40, 72]]
});
map.addControl(new mapmetricsgl.NavigationControl(), 'top-right');
</script>
</body>
</html>jsx
import React, { useEffect, useRef } from 'react';
import mapmetricsgl from '@mapmetrics/mapmetrics-gl';
import '@mapmetrics/mapmetrics-gl/dist/mapmetrics-gl.css';
const RestrictPanning = () => {
const mapContainer = useRef(null);
const map = useRef(null);
useEffect(() => {
if (map.current) return;
map.current = new mapmetricsgl.Map({
container: mapContainer.current,
style: '<StyleFile_URL_with_Token>',
center: [10, 52],
zoom: 3,
maxBounds: [[-15, 34], [40, 72]]
});
map.current.addControl(new mapmetricsgl.NavigationControl(), 'top-right');
return () => { map.current?.remove(); map.current = null; };
}, []);
return <div ref={mapContainer} style={{ height: '500px', width: '100%' }} />;
};
export default RestrictPanning;For more information, visit the MapMetrics GitHub repository.