Layer List widget won't go away

433
2
Jump to solution
09-13-2020 06:08 PM
Henry7512Custer
New Contributor II

Hello,

I'm trying to toggle a Layer list widget but the code is not working. It should respond to a click event on a button that switches its value to on/off. So far it creates the widget and adds it to the map. The part that doesn't work is when trying to remove the widget. 

Thank you in advance,

var boff=document.getElementById("onoff"); 

boff.addEventListener('click',function ()
   
    {   
      currentvalue=boff.value;
          if(currentvalue == "Off"){
            document.getElementById("onoff").value="On";
            view.when(function () {
              var layerList = new LayerList({
              view: view
           });

     // Add widget to the top right corner of the view
      view.ui.add(layerList, "top-right");
        });
 
   }
  else{
           
          view.ui.remove('layerList');
        
          document.getElementById("onoff").value="Off";

       }
    })‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
1 Solution

Accepted Solutions
KenBuja
MVP Honored Contributor

Declare layerList outside of the event listener and remove the quotes from line 21

let boff = document.getElementById("onoff");
let layerList;

boff.addEventListener('click', function () {
  currentvalue = boff.value;
  if (currentvalue == "Off") {
    document.getElementById("onoff").value = "On";
    view.when(function () {
      layerList = new LayerList({
        view: view
      });

      // Add widget to the top right corner of the view
      view.ui.add(layerList, "top-right");
    });

  }
  else {

    view.ui.remove(layerList);

    document.getElementById("onoff").value = "Off";

  }
})

View solution in original post

2 Replies
KenBuja
MVP Honored Contributor

Declare layerList outside of the event listener and remove the quotes from line 21

let boff = document.getElementById("onoff");
let layerList;

boff.addEventListener('click', function () {
  currentvalue = boff.value;
  if (currentvalue == "Off") {
    document.getElementById("onoff").value = "On";
    view.when(function () {
      layerList = new LayerList({
        view: view
      });

      // Add widget to the top right corner of the view
      view.ui.add(layerList, "top-right");
    });

  }
  else {

    view.ui.remove(layerList);

    document.getElementById("onoff").value = "Off";

  }
})
Henry7512Custer
New Contributor II

Awesome Ken, Thank you!

0 Kudos