[GIS] Giving toggle functionality to custom control in OpenLayers

openlayers

I created a custom OpenLayers 4 control named "quitarLayers" that removes two layers when I click on it.

How can I make it toggle so that it adds the two layers or removes them, depending if the layers are visible or not?

quitarLayers = function(opt_options) {

var button = document.createElement('button');
button.innerHTML = '<img class="quitalayers" src="img/layerwhite.png" 
alt="image">';

var queHaceQuitarLayers = function() {

  map.getLayers().remove(layerPrincipal);
  map.getLayers().remove(layerSecundario);

};

button.addEventListener('click', queHaceQuitarLayers, false);

var element = document.createElement('div');
element.className = 'remove-layers ol-unselectable ol-control';
element.appendChild(button);

ol.control.Control.call(this, {
  element: element,
});

 };
ol.inherits(quitarLayers, ol.control.Control);

Best Answer

here you have fine example of controlling layer groups:

http://www.acuriousanimal.com/thebookofopenlayers3/chapter02_03_layer_groups.html

https://openlayers.org/en/latest/examples/layer-group.html