I am trying to add and remove layers by passing the name of the layer variable to two separate functions and I can't seem to find any place that describes what I am trying to do. Here is an abridged version of my code:

function init(){
        var options = {
            projection: new OpenLayers.Projection("EPSG:900913"),
            displayProjection: new OpenLayers.Projection("EPSG:4326"),
            units: "m"

        map = new OpenLayers.Map('map', options);

        var drainage = new OpenLayers.Layer.Vector("Drainage Basins", {
            extractAttributes: true,
            protocol: new OpenLayers.Protocol.HTTP({
                url: "drainage_basins.gml",
                format: new OpenLayers.Format.GML()
            strategies: [new OpenLayers.Strategy.Fixed()]


I would like to call showLayer(drainage); to turn the layer on but I am not what to do:

function showLayer(layer){

and hideLayer(drainage); to turn the layer off as:

function hideLayer(layer){

Thanks for your help.

2 Answers 2


From what I understand you want to change layer visibility after the layer is added to the map by passing the layer's name only.

If this is the case your functions should look something like this:

function hideLayer(layerName) {
    var layers = map.getLayersByName(layerName);
    if(layers.length === 1) {
    else {
        console.log('big problem');

hideLayer('Drainage Basins');

An alternative is to store a reference to the layer object and act on it directly, e.g.

var drainage = new OpenLayers.Layer.Vector...


window.layers = {};
window.layers.drainage = new OpenLayers.Layer.Vector...

A web mapping application in HTML is like any other application. Save references to application resources at an user defined global scope. I would recommend use a uppercase variable name to this global scope.

There is a built in tool in OpenLayers to perform layer turn on and off. It is called a OpenLayers.Control.LayerSwitcher. Just attach it to your map by the "map" variable at end of you init() function

map.addControl( new OpenLayers.Control.LayerSwitcher() );

and you will not need those auxiliary showLayer, hideLayer functions.

  • The layer switcher does not have the functionality that I am looking for. I am building a tree view of the layers that will turn the layers on and off as an individual or as a group. Thanks for your help. Happy Holidays!
    – CDavis
    Commented Dec 22, 2012 at 2:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.