Search code examples
azureazure-maps

The 'autoResize' set to 'true' in AzureMap does not take effect when the parent size is changed


In Azure Maps, when autoResize is set to true, it seems that the map only resizes based on changes in the browser window size. It does not trigger a resize event when the dimensions of the parent element change within the page.

Changing the size of the parent element can automatically trigger a page resize.


Solution

  • You are correct and that is expected. Azure Maps uses an HTML Canvas for rendering and those don't auto resize. When Azure Maps was created, no browser had any built in method for monitoring when anything resized apart from the browser window itself. To monitor DOM element size changes you had to use a timer and step through the parent tree from your map to the root body element and check for size changes and do a bunch of calculations. This could often cause a performance issue. Since in 99% of scenarios it's not needed, Azure Maps simply monitors the browser window by default. If you know the map area/parent size has changed you can simply call map.resize() and it will recalculate the available space and fill it. Most of the scenarios I have heard where this is needed, the map is loaded either in a tab panel that is hidden, or there is some button that initiates the resize.

    That said, since then the ResizeObserver API has been made available and has good browser support (~96% of users). This is meant to address this type of issues as it's something that has been a pain for decades in all sorts of dynamic web apps, not just Azure Maps. That said, it has not yet been accepted as an official W3C API (as of July 2024) so there is no official standard way that browsers adopt this API (its possible that this works differently in different browsers and may have different performance impacts). I'm also seeing a couple of errors others are running into with this (e.g. https://hatchjs.com/resizeobserver-loop-limit-exceeded/) so these may be the reason for not adopting this yet within Azure Maps. All that said, if you want to try to use this, here is a code block.

    //Wait until the map resources are ready.
    map.events.add('ready', function () {
    
        //Setup a resize observer.
        var resizeObserver = new ResizeObserver((entries) => {
            console.log('map resized'); //Remove this after testing.
            map.resize();
        });
        
        resizeObserver.observe(map.getCanvasContainer());
    });
    

    I haven't tried this in many browsers, so be sure to test before using in production.