[GIS] openlayers – filter specific feature(s) from ol.Collection

openlayers

I have a feature collection (ol.Collection) contains number of points, lines and polygons features that originated from interactive drawing.

I want filter/select only for a certain geometry (e.g. Linestring) to write in GeoJSON format (All I can do now is looping on feature id via getFeatureById() methods)

is there any way to filter feature(s) based on its geometry type?

Best Answer

You could check that by instanceof operator comparing your geometry to ol.geom[type] where type is string representation of your type (see below). This example should do it:

function filterGeometry(collection,type){ 
  var selectedFeatures = []; 
  var featArray = collection.getArray();
  for(var i = 0;i<featArray.length;i++){
    if(featArray[i].getGeometry() instanceof ol.geom[type]){
      selectedFeatures.push(featArray[i]); 
    } 
  } 
  return selectedFeatures;//returns array of features with selected geom type 
} 
var yourCollection = new ol.Collection();//your ol.Collection with data 
var onlyLineStringArray = filterGeometry(yourCollection,"LineString");
var GeoJSONFormat = new ol.format.GeoJSON();
var GeoJSONString = GeoJSONFormat.writeFeatures(onlyLineStringArray);

Types are e.g.: Polygon, LineString, Point, MultiLineString, MultiPolygon, Circle etc., complete list of geometry types is here.

Related Question