Aragon, your answer pointed me in the right direction. Below is my final unclean code for adding layers to an array and then controling them.
In a javascript file I initialized the map and used a function to toggle visibility as follows:
//Layer array
var layersArray = [];
//Map view (Initial location)
var view = new ol.View2D({
// the view's initial state
center: ol.proj.transform([*Lat*,*Long*], 'EPSG:4326', 'EPSG:3857'),
zoom: 12
});
/* Map Initialization */
function initializeMap(){
var esribase = new ol.layer.Tile({
preload: Infinity,
source: new ol.source.XYZ({
url: 'http://server.arcgisonline.com/ArcGIS/rest/services/' +
'World_Topo_Map/MapServer/tile/{z}/{y}/{x}'
})
});
var poly1 = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/wms',
params: {'LAYERS': '*Workspace*:*Layer*', 'TILED': true}
})
});
poly1.setVisible(false);
var poly2 = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/wms',
params: {'LAYERS': '*Workspace*:*Layer*', 'TILED': true}
})
});
poly2.setVisible(false);
var poly3 = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'http://localhost:8080/geoserver/wms',
params: {'LAYERS': '*Workspace*:*Layer*', 'TILED': true}
})
});
poly3.setVisible(false);
layersArray.push(esribase); //0
layersArray.push(poly1); //1
layersArray.push(poly2); //2
layersArray.push(poly3);//3
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.ScaleLine({
units: ol.control.ScaleLineUnits.METRIC
})
]),
renderer: ol.RendererHint.CANVAS,
target: 'map',
layers: layersArray,
view:view
});
}
// Layer visibility function
function layerswitch(evt){
layersArray[evt.value].setVisible(evt.checked);
}
In the HTML I used simple checkboxes (example of poly1 toggle):
<input style='cursor:pointer' type="checkbox" value="1" onclick="javascript:layerswitch(this)" class="Cpoly1" name="poly1check" id="poly1check"/><label id="poly1checkLabel" for="poly1check">Polygon 1 Layer Switcher</label>
When you're building the layer tree you need to check the layer.getVisible()
value and assign the correct eye icon. See the example below:
http://jsfiddle.net/arcf7k77/2/
Alternatively, you could use something like knockout or angular to support the binding.
Further to your comment, in order to persist the eye icon state recursively, you would need to apply an each()
function, noting the state of the parent layer node:
http://jsfiddle.net/pamnt00b/
There's probably room for improvement, but that should get you started.
Best Answer
In Leaflet, in order to remove a layer from map, use this function
And If you want to add the same layer again, use this
I've made a copy of your fiddle and here is working fiddle for your case