Chris Chris - 7 months ago 12
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',
params:{
'LAYERS':"layergroup:mylayer", 'TILED':true
}
}),
visible: false
});
map.addLayer(featurelayer);


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.id) {
featurelayer.setVisible(true);
}
});
});


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 'this.id' 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

Isn't this.id trying to access 'layer.id' (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) {
                layer.setVisible(true);
            }
        });
    });

EDIT: Is this what you need? http://jsfiddle.net/fbma/3z1L6ttn/1/

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.