[GIS] Leaflet map loads incorrectly when inside a Bootstrap .collapse element

bootstrap-frameworkleaflet

I'm trying to create a Leaflet map which is hidden when the page loads, and revealed when the user clicks a button.

I'm trying to use the Bootstrap collapse functionality to reveal the map on a button press – sample here.

This works to show/hide the map's div – but the formatting of the map is broken, with a large empty area with no data:

enter image description here

This only occurs when the map's div has the .collapse class – if you remove that class the map loads correctly.

So the question is, how to allow a Leaflet map to load correctly when it isn't visible when the page loads?

Best Answer

https://stackoverflow.com/questions/24412325/resizing-a-leaflet-map-on-container-resize had the answer, which is to call invalidateSize on the map when the collapse event fires:

Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically

$('#demo').on('shown.bs.collapse', function (e) {
    map.invalidateSize(true);
})