[GIS] Popup filter with OpenLayers3

javascriptopenlayers

When I load my map, I load my vector overlay with this code :

var vector_overlay1 = new ol.layer.Vector({
    source: new ol.source.GeoJSON({
        url: 'json.json',
        defaultProjection :'EPSG:4326',
        projection: 'EPSG:3857'
    }), 
    name: 'NAME 1',
    style:  function(feature, resolution){
        ...
    }
});

And

map = new ol.Map({
    target: 'map',
    layers: [BASE LAYER,vector_overlay1,vector_overlay2]
});

After, I added a DIV to my map with a list of names object of my vector_overlay associate with a search button.

When a user select a value in my list, the map zoom on the object of the list and a popup appear with the informations of this object.

That is my problem, because the popup make an interrogation of all the vector layers. I try to make a filter like that :

var feature = map.forEachFeatureAtPixel(map.getPixelFromCoordinate(destination_center),
    function(feature, layer){
        return feature;
    }, null, function(layer){
        return layer.get('name') === 'NAME 1';
    }
);

But it's not the solution, and if I try :

function(layer){
return layer === vector_overlay1;
});

Firebug say : vector_overlay1 is not defined
So I've two questions :

1) Where can I choose if I want to my overlay is selectable ?

2) How can I add a layerfilter with an overlay define at the load map ?

Best Answer

First, if you are using the latest Openlayers version -- 3.5.0, you have to adapt your code to the new changes.

Specifically:

var source = new ol.source.GeoJSON({
  url: 'features.json',
  projection: 'EPSG:3857'
});

To:

var source = new ol.source.Vector({
  url: 'features.json',
  format: new ol.format.GeoJSON()
});

The "selectable part" you can do something like this (online):

map.on('click', function(evt) {
    var f = map.forEachFeatureAtPixel(
        evt.pixel,
        function(ft, layer){return ft;}
    );
    if (f && f.get('type') == 'click') {
        var geometry = f.getGeometry();
        var coord = geometry.getCoordinates();

        var content = '<p>'+f.get('desc')+'</p>';

        popup.show(coord, content);

    } else { popup.hide(); }

});
map.on('pointermove', function(e) {
    if (e.dragging) { popup.hide(); return; }

    var pixel = map.getEventPixel(e.originalEvent);
    var hit = map.hasFeatureAtPixel(pixel);

    map.getTarget().style.cursor = hit ? 'pointer' : '';
});