OpenLayers Cookbook
上QQ阅读APP看书,第一时间看更新

Avoiding the need of a base layer

There can be situations where you don't want a base layer and only want a bunch of layers to work on.

Imagine an online GIS editor where users can add and remove layers but they are not obligated to have an always visible one.

This recipe shows how we can easily avoid the requirement of setting a base layer within the map.

Avoiding the need of a base layer

How to do it...

  1. As always, create a DOM element to render the map:
    <div id="ch1_avoid_baselayer" style="width: 100%; 
    height: 100%;"></div>
    
  2. Now create a new OpenLayers.Map instance and set the allOverlays property to true:
    // Create the map using the specified DOM element 
    var map = new OpenLayers.Map("ch1_avoid_baselayer", { 
        allOverlays: true 
    });
    
  3. Add two layers to see a result. Also add the layer switcher control:
    // Add a WMS layer 
    var wms = new OpenLayers.Layer.WMS("OpenLayers WMS Basic", "http://vmap0.tiles.osgeo.org/wms/vmap0", 
    { 
        layers: 'basic' 
    }); 
    map.addLayer(wms); 
    // Add a WMS layer 
    var topo = new OpenLayers.Layer.WMS("USA Topo Maps", "http://terraservice.net/ogcmap.ashx", 
    { 
        layers: "DRG" 
    },
    { 
        opacity: 0.5 
    }); 
    map.addLayer(topo); 
    // Add LayerSwitcher control 
    map.addControl(new OpenLayers.Control.LayerSwitcher()); 
    
  4. Center the map view to some nice place:
    // Set view to zoom maximum map extent 
    // NOTE: This will fail if there is no base layer defined 
    map.setCenter(new OpenLayers.LonLat(-100, 40), 5);
    

How it works...

When the map's property allOverlays is set to true, the map ignores the isBaseLayer property of the layers.

If you expand the layer switcher control, you will see that it contains two overlay layers, no base layer, which you can show or hide and, if desired, leave a blank map without layers.

In addition, in this recipe we have used the map.setCenter() method, which needs a position, an OpenLayers.LonLat instance, and a zoom level to work.

There's more...

When working in the allOverlays mode, the lowest layer will act as base layer, although all the layers will be flagged as isBaseLayer is set to false.

See also

  • The Understanding base and non-base layers recipe
  • The Moving around the map view recipe
  • The Restricting the map extent recipe