-1

I'm trying to turn all visible feature layers to invisible in a map using Javascript and jQuery by clicking into an element. What is wrong with the following code?

$("#grayPic").click(function() {                      
    var allGuys = map.layers;
    var i, currentLayer;
    for (i = 0;  i < allGuys.length; i++) {
       currentLayer = allGuys[i];
       currentLayer.visible = false;
    };
});
  • Hi, you should tell us what exactly doesn't work. I could imagine that after your code the layers still are visible. Isn't it? – Katah Oct 31 '18 at 12:17
0

based on the information provided, I would say that the problem is that the map is not refreshed after changing the visibility of the layers. Just use map.refresh() after your loop.

$("#grayPic").click(function() {                      
  var allGuys = map.layers;
  var i, currentLayer;
  for (i = 0;  i < allGuys.length; i++) {
    currentLayer = allGuys[i];
    currentLayer.visible = false;
  };
  map.refresh();
});

UPDATED: You are not getting the layers included in the map, that's the reason you're getting a null pointer exception.

  1. First, get the layers in a proper way, for example using map.getLayersVisibleAtScale(map.getScale()). You can also access the "private" property map._layers, which was probably the one you were trying to use.
  2. Then with such information, you can perform a loop and set the visibility to false. For that I encourage you to use the method layer.hide() instead of set the property to false.

Here the snippet:

$("#grayPic").click(function() {
  var layers = map.getLayersVisibleAtScale(map.getScale());
  for (i = 0;  i < layers.length; i++) {
    currentLayer = layers[i];
    if (currentLayer.visible) {
     currentLayer.hide();
    } else {
     currentLayer.show();
    }
  };
})

P.S.: I've created a codepen that you can check for further details.

  • 1
    Sorry ... that does not work either. I am getting the following error message in the console ... Map.js:415 Uncaught TypeError: Cannot set property 'visible' of undefined at HTMLImageElement.<anonymous> (Map.js:415) at HTMLImageElement.dispatch (jquery-1.12.4.js:5226) at HTMLImageElement.elemData.handle (jquery-1.12.4.js:4878) – John Richardson Oct 31 '18 at 12:34
  • Hi John, check the new solution that has to work for you ;) – Katah Nov 2 '18 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.