OpenLayers – Working Example to Group Layers in LayerSwitcher

openlayers-2

I am looking for a nice plugin with working examples to group layers in OL 2.11/2.13.1 LayerSwitcher. I found several emails and posts explainig that GeoExt is the best way to do this, but have only access to OL.

Best Answer

There is a "unofficial" Control called OpenLayers.Control.LayerSwitcherGroups which you can find here:

https://raw.githubusercontent.com/rkj/openlayers/master/lib/OpenLayers/Control/LayerSwitcherGroups.js

Just include the Script after your OpenLayers.js and use it like this:

    var group = [hospitals, schools];
                for (var i=0; i < group.length; i++) { group[i].group = 'Hospitals + Schools'; }

    var group = [streets, police];
                for (var i=0; i < group.length; i++) { group[i].group = 'Streets + Police'; }


 map.addLayers([osm, streets, hospitals, schools, police]); 

Layerswitcher with groups Layerswitcher with groups folded / unfolded group

Apart from that there is a pretty old layerswitcher.js patch https://trac.osgeo.org/openlayers/ticket/1086 https://trac.osgeo.org/openlayers/attachment/ticket/1086/LayerSwitcher.js.patch Perhaps you could also use this and adapt it to the newer Layerswitcher.js version. The logic of this patch has been used for the Layer-Switcher-Control of HS-Layers where you can also find some more 'inspiration':

http://redmine.ccss.cz/projects/hslayers/repository/changes/trunk/source/HSLayers/Control/LayerSwitcher.js