Search code examples
javascriptcssopenlayersgis

Openlayers dynamic viewport width and height assignment


I have an openlayers map displayed in a <div> tag in a html page. i use css styles to assign the map dimensions by defining the class of the map division.

<div id="map" class="largemap"></div>

where

.largemap {
  width: 1200px;
  height: 600px;
  border: 1px solid #ccc;
}

i want to change the map dimensions dynamically depending on the user's window size, so i create a style element and assign this new class to the map division using javascript:

var mapElement = document.getElementById("map");
var sheet = document.createElement('style');
var newHeight = viewportheight-400; // previously acquired - working OK
var newWidth = viewportwidth-200; // previously acquired - working OK
var styleHTML = ".custommap {    width: "+newWidth+"px;    height: "+newHeight+"px;    border: 1px solid #ccc;}";
sheet.innerHTML = styleHTML;
document.body.appendChild(sheet);
mapElement.className = "custommap";

2 unintended things happen:

  1. just appending the style to the document changes the class of the map division;

  2. the map division still uses "old" bounds (does not center correctly on zoom);

can anyone recommend a more efficient strategy for dynamically defining the viewport in openlayers?


Solution

  • After the container size is changed you have to update the map size and recalculate bounds:

    map.updateSize();
    map.calculateBounds();
    

    You can check the OL documentation http://dev.openlayers.org/docs/files/OpenLayers/Map-js.html#OpenLayers.Map.updateSize