1

I'm using ol-layerswitcher from ol-ext, But I don't know why I can get information from unchecked or removed layers from layer switcher enter image description here

, I am going to popup information that will be able for only checked layer.

/**
 * Create an overlay to anchor the popup to the map.
 */


var overlay = new ol.Overlay({
  element: container,
  autoPan: true,
  autoPanAnimation: {
    duration: 250,
  },
});


/**
 * Add a click handler to hide the popup.
 * @return {boolean} Don't follow the href.
 */
closer.onclick = function () {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

var wmsLayersSources=[];
var queryLayers = [];
 $("#listLayers").change(function(){
     var selectProject = $("#projectname-selected option:selected").text();
          var index = projects.indexOf(`${selectProject}`);
          var geoServerWs = ws[index];

 var layers_ =($("#listLayers").val())
 
 console.log('layers_',layers_)
 if(layers_ === undefined){
     alert('Not Selected Any Layers')
 }else{

     var wmsLayers=[
     new ol.layer.Image({
         title:`${layers_}`,
           visible: true,
      source: new ol.source.ImageWMS({
       url: `http://localhost:8080/geoserver/${geoServerWs}/wms`,
       params: {'LAYERS': `${geoServerWs}:${layers_}`},
 ratio: 1,
        serverType: 'geoserver',
        imageLoadFunction: function(image, src) {
            var xhr = new XMLHttpRequest();
            xhr.responseType = 'blob';
            xhr.open('GET', src);
            xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(`${geoUserName}` + ':' + `${geoPass}`));
            xhr.onload = function() {
                var objectURL = URL.createObjectURL(xhr.response);
                image.getImage().onload = function() {
                    URL.revokeObjectURL(objectURL);
                    
    };
    image.getImage().src = objectURL;
  };
  xhr.send();
},
     
      
      })
   })
];
console.log('wmsLayers  ',wmsLayers[0])
    map.addLayer(wmsLayers[0]);
    var wmsSource =[]
    wmsSource.push(wmsLayers[0])
    wmsSource.forEach(element=>{
    wmsLayersSources.push(element.getSource())
  

    })
      queryLayers.push(`${geoServerWs}:${layers_}`)
   console.log('wmsLayersSource ', wmsLayersSources)
   console.log('queryLayers ', queryLayers)
     
}

/////Map LayerSwitcher/////


  // Control Select 
  var select = new ol.interaction.Select({});
  map.addInteraction(select);

  // On selected => show/hide popup
  select.getFeatures().on(['add'], function(e) {
    var feature = e.element;
    var content = "";
    content += "<img src='"+feature.get("img")+"'/>";
    content += feature.get("text");
    popup.show(feature.getGeometry().getFirstCoordinate(), content); 
  });
  select.getFeatures().on(['remove'], function(e) {
    popup.hide(); 
  })

 
 
    // Add control inside the map
    var ctrl = new ol.control.LayerSwitcher();
    map.addControl(ctrl);
    ctrl.on('toggle', function(e) {
        console.log('Collapse layerswitcher', e.collapsed);
    });

    // Add a layer switcher outside the map
    var switcher = new ol.control.LayerSwitcher({
        target: $(".layerSwitcher").get(0),
        // displayInLayerSwitcher: function(l) { return false; },
        show_progress: true,
        extent: true,
        trash: true,
        oninfo: function(l) { alert(l.get("title")); }
    });
  
    // Add a new button to the list 
    switcher.on('drawlist', function(e) {
        var layer = e.layer;
        $('<div>').text('?') // addClass('layerInfo')
            .click(function() {
                alert(layer.get('title'));
            })
            .appendTo($('> .ol-layerswitcher-buttons', e.li));
    });
    // Add a button to show/hide the layers
    var button = $('<div class="toggleVisibility" title="show/hide">')
        .text("Show/hide all")
        .click(function() {
            var a = map.getLayers().getArray();
           
            
            var b = !a[0].getVisible();
            if (b) button.removeClass("show");
            else button.addClass("show");
            for (var i = 0; i < a.length; i++) {
                a[i].setVisible(b);

            }

        });


    switcher.setHeader($('<div>').append(button).get(0))
        

    map.addControl(switcher);
    // Insert mapbox layer in layer switcher
    function displayInLayerSwitcher(b) {
        mapbox.set('displayInLayerSwitcher', b);
    }



////Map pointer and 
map.on('singleclick', function (evt) {
    //document.getElementById('popup-content').innerHTML ='';
    $('#popup-content').html = '';

var queryLayers =''
     
    var coordinate = evt.coordinate
  //$('#popup-content').html =''
   var viewResolution = map.getView().getResolution(); 

  
 
   wmsLayersSources.forEach(function(value, i){
       console.log('value ', value)
       console.log('value ',value.getFeatureInfoUrl)
     
     
      queryLayers = `${value["params_"].LAYERS}` //${(i<value.length -1) ?',' :''}
    console.log('querylayers is equal ', queryLayers)
    



var url = value["getFeatureInfoUrl"](
    evt.coordinate,
    viewResolution,
     'EPSG:3857',
   {'INFO_FORMAT': 'text/html','QUERY_LAYERS':`${queryLayers}`},
);
    
if (url) {
    //headers.set('Authorization', 'Basic ' + window.btoa('username' + ":" + 'password'));
    fetch(url, { 
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: new Headers({
        'Content-Type': 'text/html', 
        'Authorization': 'Basic ' +btoa(`${geoUserName}:${geoPass}`),
        
    'Content-Type': 'application/x-www-form-urlencoded',
    }),
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    }).then(function (response) {
         //console.log(response)
     
         return response.text()

         
          
      }).then(function(html) {
         
  
 $('#popup-content').html(html)

 
          });


 //end if



   }
   })
   overlay.setPosition(coordinate);

});

1 Answer 1

2

Instead of using all your WMS sources

   wmsLayersSources.forEach(function(value, i){

Only use sources which are in visible layers

   wmsLayers.forEach(function(layer, i){
       if (layer.getVisible()) {
           const value = layer.getSource();
           queryLayers = `${value["params_"].LAYERS}`
       }
       ...
1
  • Thank you so much,your answer is good, But when I did add only one layer or even I add some layers when I did uncheck all of them, last layers that unchecked and remaind in layer switcher list or even when it removed from layer switcher it can get return info! imgur.com/undefined
    – Navid
    Commented Sep 26, 2020 at 6:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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