Example on how to create a layer control in OpenLayers 3.x and above. This example uses OpenLayers 4.2.0.
This example adds a layer control to the map.
Just check the index.html for details.
A live example in :
https://htmlpreview.github.io/?https://github.com/lcalisto/ol-layer-control/blob/master/index.html
In order to make this layer control work, make sure you add basemap:boolean and name:text to your layers object.
The main function to add the control is:
showLayersControl()
Function removeLayersControl() removes the layer control.
removeLayersControl()