Search code examples
javascriptvectorpropertiesfilteringopenlayers-6

Openlayers 6: Filter point vector layer by properties before point clustering


Following the examples on Openlayers.org I created a point vector layer (with overlays etc.). The points are displayed as cluster points as in the example here:

Openlayers Cluster Example

Now, I need to filter the points according to their properties, e.g. lab_data = 'yes', sampling_year > 1990. The filtering affects the number of points inside the clusters.

I have so far not found a method to exclude features from my Source or Layer objects. I was even unsuccesful in accessing the features and their properties. From there on I could build loops and conditions.

Does anyone maybe have an idea how it is done?


// Read GeoJson point locations
var pointLocations = new ol.source.Vector({
  url: 'data/samplingLocations.json',
  format: new ol.format.GeoJSON()
});

// create point cluster
var pointCluster = new ol.source.Cluster({
    distance: 50,
    source: pointLocations
  });

// create simple style for single points and clusters
var getStyle = function(feature) {
  var length = feature.get('features').length;
  if (length > 1) {
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 20,
        fill: new ol.style.Fill({ color: "red" }),
      }),
    })
  } else {
    style = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        fill: new ol.style.Fill({ color: "black" }),
      }),
    })
  }
  return style;
};

// create a vector layer
var vectorLayer = new ol.layer.Vector({
  id: "points",
  source: pointCluster,
  style:   getStyle
});

// create the map
var map = new ol.Map({
  layers: [vectorLayer],
  target: 'map',
  view: new ol.View({
    center: [895571,5911157],
    zoom: 8,
  })
});

So far some of my unsuccessful attempts to access the properties:

console.log( pointLocations.getSource().getFeatures()[0].getProperties().values)
console.log( vectorLayer.getSource().getFeatures()[0].get('values') )

Every help is kindly appreciated!


Solution

  • You can filter with a geometry function, for example:

    var pointCluster = new ol.source.Cluster({
        distance: 50,
        source: pointLocations,
        geometryFunction: function(feature) {
          if (feature.get('lab_data') == 'yes' && feature.get('sampling_year') > 1990) {
            return feature.getGeometry();
          } else {
            return null;
          }
        }
      });