2

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.

1

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);
  }
  • What I was searching was a generic function that can be used for both Multipolygon and GeometryCollection. I solved the issue by checking the type of geometry var geom = feature.getGeometry(); if(geom instanceof ol.geom.GeometryCollection){var geoms = geom.getGeometries(); for(let i = 0, len = geoms.length; i < len; i++){ getAllGeometries(geoms[i]) } } else if(geom instanceof ol.geom.SimpleGeometry){ getAllCoordinates(geom.getCoordinates()) } Thanks for ur response @pszafer. – Johnson Jul 28 '17 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.