OpenLayers – Adding a PNG Image to a WFS Layer in OpenLayers

angularopenlayerswfs

enter image description here

style: function () {
    var path = "./../../../assets/icon/"
    var featureImage = 'track.png';

    return new Style({
        image: new Icon({
            opacity: 1,
            src: path + featureImage,
            scale: 0.5
        }),

        //text: new Text({
        //text: '',
        //font: '15px sans-serif',

        fill: new Fill({
            color: '#000000'
        }),

        stroke: new Stroke({
            color: '#838383',
            width: 1
        }),

        //offsetX: 0,
        //offsetY: -7
    })
}

This is the code which I have added after my WFS layer, but image is not added to the layer.

Best Answer

To display an image on a LineString you will need a style array, one style with geometry function which returns a Point geometry (e.g. the midpoint of the line) where the image is to be placed, and another style to display the original LineString geometry.

[
  new Style({
    geometry: function(feature) {
      const geometry = feature.getGeometry();
      if (geometry.getType() === 'LineString') {
        return new Point(geometry.getCoordinateAt(0.5));
      } else {
        return geometry;
      }
    },
    image: new Icon({
        opacity: 1,
        src: path + featureImage,
        scale: 0.5
    }),
  }),
  new Style({
    //text: new Text({
    //text: '',
    //font: '15px sans-serif',

    fill: new Fill({
        color: '#000000'
    }),

    stroke: new Stroke({
        color: '#838383',
        width: 1
    }),
  }),
]

If you need multiple icons on the LineString the geometry function would need to return a MultiPoint geometry, for example for 6 points including the start and end of the line

geometry: function(feature) {
  const geometry = feature.getGeometry();
  if (geometry.getType() === 'LineString') {
    const showPoints = 6;
    const points = [];
    for (let i = 0; i < showPoints; i++) {
      points.push(geometry.getCoordinateAt(i / (showPoints - 1)));
    }
    return new MultiPoint(points);;
  } else {
    return geometry;
  }
},
Related Question