[GIS] way to filter vector layer with JSON source in OL3

filtergeojsonopenlayersvector-layer

Is it possible to filter the ol.layer.Vector with a JSON source and display only specific features?

My vector layer looks like this:

var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: 'http://vagrant-test.local.com/json/countries.js'
      }),
      style: function(feature) {
        return style;
      }
  });

I check the ol3 documentation and didn't find some filter functionality.

Best Answer

You would need to create your own filter. You can do this by getting the JSON via ajax:

var jsonResult;

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: function(data) {
       jsonResult = data;
    }
});

https://api.jquery.com/jquery.ajax/

Then you will need to delete the elements you do not want from jsonResult, and re-stringify it. You'll need to be somewhat familiar with the structure of the GeoJSON data you're working with, GeoJSON in general so you don't delete something OL needs to parse it, and working with JSON.

Then you can read the remaining elements into features and add them to your source:

var geojsonFormat = new ol.format.GeoJSON();
var features = geojsonFormat.readFeatures(stringifiedFilteredJSON);
layerSource.addFeatures(features);