Search code examples
javascriptopenlayers

Get information from several layers using forEachFeatureAtPixel method


I want to obtain information from several layers, I am using the forEachFeatureAtPixel method, but when I get the results I only get the first result, When in the browser response, I see that the JSON it returns has more results. When I used the getFeaturesAtPixel method, I got all the results through a FOR loop. But now I don't know how to get all the results.

map.on("click", function (evt) {
    var result = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
        return { feature, layer };
    });
    if (result) {
        var feature = result.feature;
        var layer = result.layer;
        if (layer === vec01) {
            contINFO.innerHTML = '<b>One name:' + feature.get('one_name') + '<b>'
        }else if (layer === vec02) {
            contINFO.innerHTML = '<b>Other name:' + feature.get('other_name') + '</b><b>Percent: ' + feature.get('percent') + '</b>'
        }
    }
});

Solution

  • Returning any truthy value in the callback will stop the detection at the first feature. To get all features do not return a value and build up the results from each feature

    const info1 = document.getElementById("info1");
    map.on("click", function (evt) {
        var info1Count = 0;
        var contCount = 0;
        map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
            var info1HTML = '';
            var contHTML = '';
            if (layer === vec01) {
                info1HTML = JSON.stringify(
                    Object.entries(feature.getProperties()).filter(function (entry) {
                    return entry[0] !== "geometry";
                    })
                );
                contHTML = '<b>One name: ' + feature.get('one_name') + '<b>'
            }else if (layer === vec02) {
                info1HTML = JSON.stringify(
                    Object.entries(feature.getProperties()).filter(function (entry) {
                        return entry[0] !== "geometry";
                    })
                );
                contHTML = '<b>Other name:' + feature.get('other_name') + '</b><b>Percent: ' + feature.get('percent') + '</b>'
            }
            if (info1HTML != '') {
              if (info1Count == 0) {
                info1.innerHTML = '';
              } else {
                info1.innerHTML += '<br>';
              }
              info1.innerHTML += info1HTML;
              info1Count ++;
            }
            if (contHTML != '') {
              if (contCount == 0) {
                contINFO.innerHTML = '';
              } else {
                contINFO.innerHTML += '<br>';
              }
              contINFO.innerHTML += contHTML ;
              contCount++;
            }
        });
    });