Skip to content

Openlayers initial extent

An answer to this question on Stack Overflow.

Question

According to the OpenLayers documentation, the constructor, OpenLayers.Map(), allows for an additional property extent which is "The initial extent of the map" (see here).

However, I cannot get it to have any effect. I know I can set an initial extent by calling .zoomToExtent() after constructing the map. But I would like to use this extent property because I set a zoomend event in the eventListeners property but don't want it to trigger with an initial call to .zoomToExtent(). Does anyone have a clue how to use this extent property?

This is the code that isn't working

map = new OpenLayers.Map('map',{
        extent: bounds,
        layers: [osmLayer,vectorLayer],
        projection: "EPSG:900913",
        eventListeners: {
            zoomend: function() {
                //..zoomend event listener code
            }
        }
    });

In the above example:

  • bounds is a valid OpenLayers.Bounds object
  • osmLayer and vectorLayer are valid OpenLayers.Layer objects of which osmLayer is the base layer.

What happens with above code is that the map is completely zoomed out (in fact you can't actually see anything) and any attempts to pan results in errors being thrown. To get to map into a correct state the user has to zoom in and then panning works again and you can see the map.

Answer

I'm afraid I'm not sure off-handedly how to make the code you listed work, however the following alternative has worked for me:

map = new OpenLayers.Map('map',{projection: new OpenLayers.Projection("EPSG:4326")});
//ADD A BUNCH OF LAYERS AND SUCH HERE
//Set map center to this location at this zoom level
map.setCenter(new OpenLayers.LonLat(-93.9196,45.7326),5);

As a last resort, you could put a line at the beginning of your zoom function:

if(!map_ready) return;

And then set the variable map_ready to true at the appropriate time.