OpenLayers 2 JavaScript – How to Filter Vector Layer Features

javajavascriptopenlayers-2

I'm using OpenLayers – 2.11,GeoServer 2.13, ExtJS 3.4, and Java for developing GIS based web applications.

I have added some point features in one vector layer.
It has id, name, address, etc.

Can I filter some points with 'name' from that vector layer and only show matched features in vector layer?
I have to filter some points and later I have to show all hidden data.

eg:
enter image description here

Best Answer

Since you already setup the stylemaps for diplaying labels. You can easily do this by checking the feature attribute value of the required field with the search text

Try the below code to search in attributes

//JS code
    function search() {
    var search_name = document.getElementById("search_text").value;
    var features = layer.features;
    layer.destroyFeatures();
    for(var i=0; i< features.length; i++) {

     //features[i].attributes.name. you have the attribute field "name"

      if(features[i].attributes.name === search_name) {
        layer.addFeatures([features[i]])
      }
    }

    layer.redraw();
    }

<!-- HTML stuff  -->
    <input type="text" id="search_text" />
    <button onclick="search()">Search</button>

Update: hide/show using renderIntent

    //JS code

        function search() {
        var search_name = document.getElementById("search_text").value;
        var features = layer.features;
        for(var i=0; i< features.length; i++) {

         //features[i].attributes.name. you have the attribute field "name"

         //hide  a feature by default
          features[i].renderIntent = "delete"; 
          if(features[i].attributes.name === search_name) {
           //show a feature value of name attribute is search_name 
            features[i].renderIntent = "default" 
          }
        }

        layer.redraw();
        }

The second method becomes faster as renderIntent="delete" will set the css property display: none;(hiding) and renderIntent="default" will use the default rendering from your stylemap obivously showing the features.

Related Question