Sheyar
Sheyar

Reputation: 51

Get a feature properties for the layer which has been clicked in OpenLayers 3

I am working on OpenLayers 3 with Geoserver, I have four vector layers, I am using singleclick event to get properties for each feature and show them in a popup window.

Now my problem that when i click on a feature from the highest layer i get all properties from all layers which are lower, I used forEachFeatureAtPixel but i don't know how to specify it for each layer!

Here is my code:

var OpenMeters = function (evt) {
content.innerHTML = "";
var feature = map.forEachFeatureAtPixel(evt.pixel,
    function (feature, layer) {
        if (feature) {
            var coord = map.getCoordinateFromPixel(evt.pixel);
            var objeto = feature.getProperties(),propiedades;
            for (propiedades in objeto)
            {
              content.innerHTML += '<b>' + propiedades + '</b> : <i><b>'+ objeto[propiedades]+'</b></i><br />';
            }
            overlay.setPosition(coord);
        } else {
            overlay.setPosition(undefined);
        }
    });
};

map.on('singleclick', OpenMeters);

var select = new ol.interaction.Select();
map.addInteraction(select);

How can i specify singleclick event for each layer ? Any help ?

Upvotes: 4

Views: 7174

Answers (1)

oterral
oterral

Reputation: 471

You can't specify a single click for each layer but according to the api doc of forEachFeatureAtPixel function :

Returns:

Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. 

So if your return a value on the first call of the callback you will get the first feature you hit:

var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
  return feature;    
});
if (feature) {
  var coord = map.getCoordinateFromPixel(evt.pixel);
  var objeto = feature.getProperties(),propiedades;
  for (propiedades in objeto) {
    content.innerHTML += '<b>' + propiedades + '</b> : <i><b>'+ objeto[propiedades]+'</b></i><br />';
    }
    overlay.setPosition(coord);
  } else {
    overlay.setPosition(undefined);
  }
};

SNIPPET NOT TESTED

Upvotes: 2

Related Questions