Skip to content

Instantly share code, notes, and snippets.

Last active January 6, 2023 09:04
Show Gist options
  • Save danswick/fc56f37c10d40be62e4feac5984250d2 to your computer and use it in GitHub Desktop.
Save danswick/fc56f37c10d40be62e4feac5984250d2 to your computer and use it in GitHub Desktop.
Mapbox GL JS interactive map.resize()

Intentionally break your map canvas using the resize container button, then fix it again using the fix map button. This little demo is designed to show off how Mapbox GL JS's map.resize() method can fix a squished or stretched map canvas by telling the map to 1) check the size of its container, then 2) trigger a re-render. This method is useful for applications where the map's container might be resized interactively through a sliding, expanding, contracting, or interactively hidden HTML element.

<!DOCTYPE html>
<meta charset='utf-8' />
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src=''></script>
<link href='' rel='stylesheet' />
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; transition: all 0.3s; }
.button { color: #fff; background-color: #555; padding: 1em; margin: 1em; position: absolute; right: 1em; top: 1em; border-radius: 0.5em; border-bottom: 2px #222 solid; cursor: pointer; }
#resizeMap { top: 5em; }
<div id='map'></div>
<div id='resizeDiv' class='button'>Resize container</div>
<div id='resizeMap' class='button'>Fix map</div>
mapboxgl.accessToken = 'pk.eyJ1IjoiZGFuc3dpY2siLCJhIjoiY2l1dTUzcmgxMDJ0djJ0b2VhY2sxNXBiMyJ9.25Qs4HNEkHubd4_Awbd8Og';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9', //stylesheet location
center: [-74.50, 40], // starting position
zoom: 9 // starting zoom
var biggerSmaller;
map.on('load', function() {
var mapCanvas = document.getElementsByClassName('mapboxgl-canvas')[0];
var mapDiv = document.getElementById('map');
var breakButton = document.getElementById('resizeDiv');
var fixButton = document.getElementById('resizeMap');
breakButton.onclick = function() {
if (biggerSmaller !== 'smaller') { = '50%'; = '100%';
biggerSmaller = 'smaller';
} else { = '150%'; = '100%';
biggerSmaller = 'bigger';
fixButton.onclick = function() {
Copy link

pjobson commented Apr 17, 2019

Thanks for posting this. I was having an issue where Angular was doing an animation which made half a map display. Wound up doing the resize after a 250ms timeout. Seems to work well enough.

Copy link

Sefibrah commented Jan 6, 2023

In my Angular web app, I've also had this map.resize() not being triggered issue. I can confirm that using RxJs's delay operator like this: delay(50) did the trick for me. However, I have no clue why 😅. Thanks @pjobson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment