If the name of my layer in openlayers is "olayer". And if i want to set its visibility to true. Then the simple code is


But if i want to set the visibility by storing the layer's name in a different variable like this:

     var vari="olayer";        

This won't work because its taking "vari" as the name of the layer instead of the string stored in variable "vari".

  • 1
    As you have written it, vari equals a string olayer, so the behaviour yoobservce is expected. If you want an object reference, then use, 'var vari = olayer; – John Powell Nov 27 '15 at 8:25

"olayer" is just a string instead of a reference. As such it does not provide a method called SetVisibility.

When you want to set olayers properties (be aware that there are no quotes) or call its methods you have to use a reference to it:

var vari = olayer;

You can get a layer by name using getLayersByName.

From that you can call SetVisibility:

var layer = map.getLayersByName("olayer")[0];
  • i mean can't i use a variable that stores the name of the layer for using setvisibility function? i.e if i use a variable it returns the name of the layer when calling a function. – user2711295 Mar 5 '16 at 9:16

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.