[GIS] Render and style multiple geometry features in OpenLayers

openlayers

Using OpenLayers 4.2.0.

I have a feature with two geometries:

var feature = new ol.Feature({
  geometry: new ol.geom.Polygon(polyCoords),
  labelPoint: new ol.geom.Point(labelCoords),
  name: 'My Polygon'
});

Is it possible to render all of them at a time and style each geometry individually? Particularly I need to render the geometry and display the name in the labelPoint.

If I set a style to the feature it is applied to the geometry only. See this fiddle.

I also tried it via geometry collection

var feature = new ol.Feature({
  geometry: new ol.geom.GeometryCollection([
    new ol.geom.Polygon(polyCoords),
    new ol.geom.Point(labelCoords)
  ]),
  name: 'My Polygon'
});

but in this case the name is rendered twice. See this fiddle.

Best Answer

Instead of using a geometry collection, use features with two geometry columns. Something like

var feature = new ol.Feature({
  geometry: new ol.geom.Polygon([[[-10e6, 6e6], [10e6, 6e6], [10e6, -6e6], [-10e6, -6e6]]]),
  point: new ol.geom.Point([0,3e6]),
  name: 'My Polygon'
});

Then create two styles, one for the main geometry and one for the second one ('geometry: point'):

var style = [
  new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: 'red',
      width: 2
    })
  }), 
  new ol.style.Style({
    geometry: 'point',
    image: new ol.style.Circle({
      radius: 5,
      fill: new ol.style.Fill({
        color: 'blue'
      })    
    }),
    text: new ol.style.Text({
      text: (feature.get('name')).toString(),
      font: '30px sans-serif',
      fill: new ol.style.Fill({
        color: 'red'
      })
    })
  })
];