[GIS] Get all the coordinates of a feature in OpenLayers 4

coordinatesgeojsonjavascriptopenlayerspolygon

I am trying to highlight all the vertices (coordinates) of polygon by adding ol.style.Style() as in following code snippet.

var polygonStyles = new ol.style.Style({
      image: new ol.style.Circle({
        radius: 5,
        fill: new ol.style.Fill({
          color: 'orange'
        })
      }),
      geometry: function(feature) {
        // return the coordinates of the first ring of the polygon
        var coordinates = feature.getGeometry().getCoordinates()[0]; //throws error if feature.getGeometry() returns an Object of GeometryCollection
        return new ol.geom.MultiPoint(coordinates);
      }
    })

But the problem is if the polygon Geometry is of type GeometryCollection then var coordinates = feature.getGeometry().getCoordinates()[0]; throws error (ol.geom.GeometryCollection does not have function getCoordinates() but again another getGeometries() function).
Is there any method or any other workaround to get all the coordinates of the feature regardless of the type of Geometry returned from feature.getGeometry() function. The polygon is loaded into the vector as below.

var polygon = new ol.layer.Vector({
            source: new ol.source.Vector({
                format: new ol.format.GeoJSON(),
                url: 'data.json'
            }),
            style: polygonStyles
        })

where 'data.json' can have geometry of type either MultiPolygon or GeometryCollection as of now.

Best Answer

Multipolygon has getCoordinates() method, but if you have GeometryCollection you should use somethink like this:

geometry: function(feature) {
    var geometries = feature.getGeometries();
    var coordinates = [];
    for (var key in geometries){
       //I use concat so I don't have array of arrays
       var coordinates.concat(geometries[key].getCoordinates());
    }
    return new ol.geom.MultiPoint(coordinates);
  }
Related Question