Search code examples
formsopenlayersweb-feature-servicefilterattribute

How do I use a input value from select option form to filter features in openlayers 7.3.0?


I have a select filter form. I want to use the input value from options to filter features and return with a specific file. The return style will not work inside the event handler.

How do I solve this thanks for your help.

const funStyle = (feature) => {
  
  function onchange(event) {
      if (feature.get('PROVINCE') == event.target.value) {

          //Returning style here doesn't work
          //return selectedStyle

      }
  }
  
  document.getElementById('provinces').addEventListener('change', onchange)
  // Here it works but with not filter
  return selectedStyle
}

Here is my vector layer ->

const vector =
  new VectorLayer({
      source: new VectorSource({
          format: new GeoJSON(),
          url: wfsUrl,
      }),
      style: funStyle,
      name: 'Vector',
  });

Thanks for your help :)

I have tried returning the style inside and eventhandler which doesn't display any features on map.


Solution

  • You can use a global variable for the filter value, so everything can be done in scope. Also call the changed() method on the layer so make it re-render when the filter is changed.

      let filterValue;
    
      const funStyle = (feature) => {
          if (feature.get('PROVINCE') == filterValue) {
              return selectedStyle
          }
      }
    
      const vector = new VectorLayer({
          source: new VectorSource({
              format: new GeoJSON(),
              url: wfsUrl,
          }),
          style: funStyle,
          name: 'Vector',
      });
    
      function onchange(event) {
          filterValue = event.target.value;
          vector.changed();
      }