Chris Chris - 1 year ago 63
Javascript Question

Open Layers 3 layer visibility - problems passing variables

I have got together a pretty basic function which turns on a layer I have on my map.

This is the code for initialising the layer:

var featurelayer;

featurelayer = new ol.layer.Tile({
name: 'featurelayer',
source: new ol.source.TileWMS({url: 'http://myserver/geoserver/wms',
serverType: 'geoserver',
'LAYERS':"layergroup:mylayer", 'TILED':true
visible: false

I have a list item on my site which when clicked activates a function that I am using to try to turn the layer on. My html and jQuery function is below:

<li class='last'><a href='#'><i class="fa fa-circle text-info"></i><span> Flood Zone 3b (Functional Floodplain)</span></a></li>

$("a.layer").click(function() {
map.getLayers().forEach(function(layer) {
if (layer.get('name') === {

This code actually works, it displays the layer on the map. My problem is I will have more than one layer, and ideally I want to be able to pass the ID from my list item which is the same name as the layer to my setVisible event.

I cannot seem to work out how to do this as my console log is always returning undefined; I have tried creating a variable which I am equaling to '' but that doesn't work - do I need to pass my ID through my click function? Why am I receiving an undefined error if it is registering that my layer name matches my list item ID?

Thanks for any help you can give!

Answer Source

Isn't trying to access '' (which may be undefined) as it's inside the forEach loop?

Try getting the id before entering the loop:

 $("a.layer").click(function () {
        var lid = $(this).attr('id');
        map.getLayers().forEach(function (layer) {
            if (layer.get('name') == lid) {

EDIT: Is this what you need?

I've added ids to both li items, and the click event is related to class 'last'. Also, visibility is set on the layer object of the iteration.