OpenLayers Map Redraw – Redrawing Map after Container Resize in OpenLayers

javascriptopenlayers-2

In my web application, I want to enable users to set the size of the map container.

Everything worked fine when the container was expanded slightly (apparently this is because the tiles that were just behind the border were already loaded). However, when the container is expanded significantly (in the following example, from 300 to 1000px in width), there is blank space left.

How to make the map redraw and adapt to the new size?

Calling redraw() on all layers didn't help. Neither did zooming in and out.

I tested this with the described results in Opera, Chrome and Firefox.
In IE8, surprisingly, the problem didn't occur and the map automatically adapted.

A simplified webpage for testing:

<html>
  <head>
    <style>
      #mapbox { 
        width: 300px;
        height: 500px;
        border: 1px solid black;
      }
    </style>

    <script src="http://openlayers.org/api/OpenLayers.js"></script>
  </head>

  <body>
    <div id="mapbox"></div>
    <input type="button" id="test" value="resize">

    <script>    
      var map = new OpenLayers.Map('mapbox');
      map.addLayer(new OpenLayers.Layer.OSM());      

      map.setCenter(
        new OpenLayers.LonLat(1000000, 7000000), 5);

      document.getElementById('test').onclick = function() {
        document.getElementById('mapbox').style.width = '1000px';
      }
    </script>
  </body>
</html>

Best Answer

You need to call the API to update map size.

https://openlayers.org/en/latest/apidoc/module-ol_Map-Map.html#updateSize

Here's how we do it

window.onresize = function()
{
  setTimeout( function() { map.updateSize();}, 200);
}

You can see we did a slight delay, and honestly I don't remember the exact reason why, but we had to give it a slight wait before calling API to resize itself.