OpenLayers GetFeatureInfo – Conditional Layer Visibility Query

getfeatureinfoopenlayers

I'm using the following code in Open Layers 6, and it shows the feature info, even if the layer is not visible

map.on('singleclick', function(evt){
        document.getElementById('info').innerHTML = '';
        var viewResolution = vista.getResolution();
        var url = wmsLayer3.getSource().getFeatureInfoUrl(
            evt.coordinate, viewResolution, 'EPSG:25830', {'INFO_FORMAT': 'text/html'});
        if (url) document.getElementById('info').data = url;
    });

How should it be modified to show the feature info only if the layer is visible?

Best Answer

You can check the visibility of the layer in the callback function, and exit if not visible:

map.on('singleclick', function(evt){
        if (!wmsLayer3.getVisible()) return;
        document.getElementById('info').innerHTML = '';
        var viewResolution = vista.getResolution();
        var url = wmsLayer3.getSource().getFeatureInfoUrl(
            evt.coordinate, viewResolution, 'EPSG:25830', {'INFO_FORMAT': 'text/html'});
        if (url) document.getElementById('info').data = url;
    });
Related Question