popupopenlayers-3geoservergetfeatureinfo

get feature attributes from multiple Geoserver layers on click - open layers 3


I am trying to get attributes from multiple layers on a map click, using OpenLayers 3 and layers served from Geoserver.

I found this snippet but it is using an older version of Open Layers, I haven't found anything that works the same way with Open Layers 3

http://dev.openlayers.org/examples/getfeatureinfo-popup.html


Solution

  • this seems to work..simple variation of the first answer - this will retrieve and display attributes from multiple layers and from multiple features in each layer, if there are overlapping features

    var layerlist = [wmsLayer, wmsLayer2];
    var info = [];
    
    map.on('singleclick', function(evt) {
      info = [];
    
    for (i=0; i<layerlist.length; i++)
      getInfo(evt, layerlist[i]);
    });
    
    function getInfo(evt, layer) {
      var resolution = map.getView().getResolution();
      var coordinate = evt.coordinate;
      var pixel = evt.pixel;
      var thislayer = layer.getSource().getParams().LAYERS;
    
    
      var url = layer.getSource().getGetFeatureInfoUrl(evt.coordinate,
        resolution, 'EPSG:3857', {'INFO_FORMAT': 'application/json', 'FEATURE_COUNT': 50 });
    
    if (url) {
          var parser = new ol.format.GeoJSON();
            var lookup = {};
           $.ajax({url: url,
              dataType: 'json',
              success:function(response) {
                var result = parser.readFeatures(response);
                if ((result.length > 0) && (wmsLayer.getVisible()==true)) {
                  for (var i = 0, ii = result.length; i < ii; ++i) {
                   var text = result[i].get("id");
                   var param_name; 
                   // to populate different field values from different layers in info popup
                   if (thislayer == 'thisname' ){
    
                     param_name = result[i].get("param1");
                   } else {
                     param_name = result[i].get("param2");
                   }
    
                        info.push( param_name); 
                  }
                    content.innerHTML  = '<p><strong>ID: </strong>' + info.join(', ');
    
    
               overlay.setPosition(coordinate);
            }
          }
        });
      }