How to fix canvas size in Mapbox GL?

Andres picture Andres · Feb 10, 2017 · Viewed 8.1k times · Source

I'm using Mapbox GL to show a map and crop a fixed size image from the center of it. It works great for a particular resolution I designed it (1920x1080) but when I started to make the page responsive where the map styles width and height changes, the canvas size also started to change!

So, when I crop the image the size should be always different because 300px on a 900px canvas it's not the same map area as 300px on a 2000px canvas. The canvas size even changes drastically if I change the device type from Desktop to Mobile in Chrome.

Is there any way to make the canvas DOM size fixed while scaling the entire map with CSS attributes as it's done on a normal canvas? I tried doing trackResize: false and the canvas DOM size stays fixed but the map is not scaled to fit the container neither.

Answer

saike picture saike · Aug 21, 2019

for version: "mapbox-gl": "^1.2.1", set height for canvas map container class:

.mapboxgl-canvas-container {

    height: 100vh;

}

then on map load event:

onMapLoaded(event) {

    event.map.resize();

}