[GIS] Add layer in Openlayers using layer variable passed to a function with setVisibility

javascriptopenlayers-2

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()]
        });

        map.addLayers([drainage]);
}

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

function showLayer(layer){
    layer.setVisibility(true);
}

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

function hideLayer(layer){
    layer.setVisibility(false);
}

Thanks for your help.

Best Answer

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) {
        layers[0].setVisibility(false);
    }
    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...

becomes

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