Atlaslog / Field Notes / Loading & display
Field note · Loading & display
Map misaligned inside a modal, drawer or tab
Quick answer
A map initialised while display: none gives the library a 0x0 container, so only the top-left corner is drawn later. Dragging or zooming sometimes repairs it because those gestures force an internal size recalculation.
Symptom
- After the modal opens, only half the map is drawn and the rest is grey until you drag or zoom.
- Switching back to a tab shows a blank map that only reappears after a zoom.
- The map behaves normally on the main page and only fails inside the dialog.
Checklist
- Determine whether the container was hidden at the moment of initialisation.
- If so, create the map after the modal transition ends rather than on page load.
- If initialisation must happen early, call invalidateSize() or updateSize() when the container becomes visible.
- Attach a debounced ResizeObserver for layouts that change size dynamically.
- For Cesium, call viewer.resize() or viewer.scene.requestRender(), especially with requestRenderMode enabled.
Fix
Initialise once the container is visible, or call map.invalidateSize() in Leaflet / map.updateSize() in OpenLayers on show; debounce a ResizeObserver so layout-driven size changes are handled centrally.
Code
function openDialog() {
dialog.style.display = 'block';
requestAnimationFrame(function () {
if (!map) {
map = L.map('map', { center: [39.9, 116.4], zoom: 12 });
L.tileLayer(url).addTo(map);
}
});
}// Leaflet
map.invalidateSize();
// OpenLayers
map.updateSize();
Watch out
- Calling invalidateSize() during the open animation, which measures an intermediate size.
- Creating a new map instance every time the modal opens, leaking listeners and canvases.
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Atlaslog (2026). Map misaligned inside a modal, drawer or tab. https://www.jingweizhi.com/en/cookbook/map-in-modal.html (accessed 2026-11-03).