OpenLayers – Specifying Popup for Specific Layer in OpenLayers 3

javascriptopenlayerspopup

I am using the function to define popup contents in a map, and right now, it createa a popup for every feature I click on the map, no matter what layer it is in. I would like this popup to appear only for features within one layer. I'm sure there is a way I can specify this in the function, but I'm not sure how. I tried using this for line 6 if (feature && layer === layerVector) { but it gave me an error saying that layer is undefined. layerVector is the variable name for the layer I want to use the popup for. Can anyone help? Here is the code:

map.on('click', function(evt) {
  var feature = map.forEachFeatureAtPixel(evt.pixel,
      function(feature, layer) {
        return feature;
      });
  if (feature) {
    popup.setPosition(evt.coordinate);
      content.innerHTML = '<b>Parcel No: </b>'+
      feature.get('parcel')+'<br>'+
      '<b>Owner: </b>'+
      feature.get('primowner')
  } 
});

Best Answer

When doing forEachFeatureAtPixel, you should do any filtrering inside the callback function. You have the feature and it's layer available as arguments.

This would return the first clicked feature:

var feature = map.forEachFeatureAtPixel(pixel,
  function(feature, layer) {
    return feature;
  }
);

This would return the first clicked feature in targetLayer:

var feature = map.forEachFeatureAtPixel(pixel,
  function(feature, layer) {
    if (layer == targetLayer) {
      return feature;
    }
  }
);

But when you know that you are only interested in a set of specific layers, a simple optimization is to use the fourth argument: the layer filter function.

The layer filter function is called once for each vector layer, and determines if the layer should be used when looking for features at the given pixel. The code above would trigger an unnecessary spatial lookup in all vector layers, while the code below will only look for matching features in targetLayer:

var feature = map.forEachFeatureAtPixel(pixel,
  function (feature, layer) {
    return feature;
  },
  this, // third argument, determines 'this' for the callback
  function (layer) {
    return layer == targetLayer;
  }
);