I have two overlays in OpenLayers and I don't want them to show at the same time. Here's the code I'm using so that when someone uses the layer switcher the other layer turns off. The problem is this code triggers the 'changeLayer' event listener again and the function hides both layers.
Is there another way I can force the user to only view one layer at a time? Ideally I would want radio buttons in the layer switcher box instead of checkboxes.
var mapLayerChanged = function(event) {
if (event.layer.name == "Sea Cells") {
$('.toolbar .view-options').show();
map.layers[1].setVisibility(false);
} else if (event.layer.name == "Coast Cells") {
$('.toolbar .view-options').hide();
map.layers[2].setVisibility(false);
}
}
map = new OpenLayers.Map( {
div : 'map',
panDuration : 100,
numZoomLevels : 18,
maxResolution : maxResolution,
maxExtent : maxExtent,
displayProjection : new OpenLayers.Projection( "EPSG:2193" ),
controls : [],
eventListeners: {
"changelayer" : mapLayerChanged
}
} );
As per definition of changeLayer on http://dev.openlayers.org/apidocs/files/OpenLayers/Map-js.html
changelayer
triggered after a layer name change, order change, opacity change, params change, visibility change (actual visibility, not the layer’s visibility property) or attribution change (due to extent change). Listeners will receive an event object with layer and property properties. The layer property will be a reference to the changed layer. The property property will be a key to the changed property (name, order, opacity, params, visibility or attribution).
so,
property
.map.layers[1].setVisibility(false);
Below code would solve your problem,
function mapLayerChanged(event){
if(event.property = "visibility"){
if (event.layer.name == "Sea Cells") {
if(event.layer.getVisibility()){
$('.toolbar .view-options').show();
map.getLayersByName("Coast Cells")[0].setVisibility(false);
}
} else if (event.layer.name == "Coast Cells") {
if(event.layer.getVisibility()){
$('.toolbar .view-options').hide();
map.getLayersByName("Sea Cells")[0].setVisibility(false);
}
}
}
}
It first check if event is fired because of visibility change only (through event.property == "visibility"
condition) and it will fire only if current layer's visibility is true (through event.layer.getVisibility() condition)
Above code should work as per your requirement.