Camera and view control
Quick answer
This tutorial shows how a Leaflet map view is defined by a center and a zoom level and compares the four movement methods: setView, panTo, flyTo and fitBounds. It explains flyTo options such as duration and easeLinearity, why fitBounds needs an explicit maxZoom, and how to wait for moveend before reading the new bounds. It then covers pixel and geographic coordinate conversion plus invalidateSize. Readers can stage smooth camera moves and keep overlays aligned after layout changes.
Key points
- Use fitBounds with padding and maxZoom so a single point is not zoomed to street level.
- Call map.once('moveend') before flyTo; the center is still the origin right after the call.
- Call map.invalidateSize() after the sidebar, tab or window changes the container size.
Example
var map = L.map('map').setView([39.907359, 116.391263], 11);
map.flyTo([31.230416, 121.473701], 12, {
duration: 2.2, // 秒
easeLinearity: 0.3
});
var region = L.latLngBounds([39.80, 116.20], [40.05, 116.55]);
map.fitBounds(region, {
padding: [30, 30], // 四边留白,像素
maxZoom: 14, // 防止小范围被放大过头
animate: true
});function flyAndThen(target, zoom, done) {
map.once('moveend', function () {
done(map.getBounds());
});
map.flyTo(target, zoom);
}
flyAndThen([31.230416, 121.473701], 13, function (bounds) {
console.log('抵达', bounds.toBBoxString());
});
Notes
- Mixing flyTo with setView cuts the running animation and fires moveend only once.
- All conversions assume WGS84; GCJ-02 tiles with WGS84 input shift features by hundreds of meters.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). Camera and view control. https://www.jingweizhi.com/en/leaflet/tutorials/view-control.html (accessed 2026-11-03).