2

I'm trying to add an icon on the map with OpenLayers 5.

I've tried to follow the Openlayers sample on the site, but without success (https://openlayers.org/en/latest/examples/icon.html)

I believe that the problem may be the Style, because when I remove it from the feature, a point is shown on the map, however when I try to add a style to that Point (that it is the icon), nothing is shown on the map.

I send below the code that I use:

import Point from 'ol/geom/Point'
import { Icon, Style } from 'ol/style.js'
// or
// import Icon from 'ol/style/Icon'
// import Style from 'ol/style/Style'

...

const vectorMarkerSource = new VectorSource()

const vectorMarkerGroup = new VectorLayer({
    source: vectorMarkerSource
})

...

this.olmap = new Map({
    target: 'map',
    layers: [
        baseLayerGroup, vectorMarkerGroup
    ],
    view: this.view
})

...

var iconFeature = new Feature({
    geometry: new Point([0, 0]),
    projection: 'EPSG:4326'
})

// I've already tried the two options of 'src'
var iconStyle = new Style({
    image: new Icon(/** @type {module:ol/style/Icon~Options} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: '@/assets/img/marker/marker-blue.png'
        // src: '../../assets/img/marker/marker-blue.png'
    }))
})

iconFeature.setStyle(iconStyle)

vectorMarkerSource.addFeature(iconFeature)

Thank you in advance.

Moritz
  • 378
  • 5
  • 14
rmmariano
  • 896
  • 1
  • 18
  • 32
  • 1
    Does the console show a 404 error for marker-blue.png? – Mike Apr 01 '19 at 11:56
  • 1
    No, it does not. On console is shown nothing. Fortunately I accidentally have found a solution for this question and I answered below. Thank you so much for your help. – rmmariano Apr 01 '19 at 12:20

1 Answers1

1

I have discovered a solution accidentally. I was reading another code to solve another problem and on this code the creator used the following approach to insert an icon.

import markerIconBlue from '@/assets/img/marker/marker-icon-2x-blue.png'

var iconStyle = new Style({
    image: new Icon(/** @type {module:ol/style/Icon~Options} */ ({
        anchor: [0.5, 46],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        src: markerIconBlue
    }))
})

Fortunately, this approach have worked to me and I hope that this help others.

Moritz
  • 378
  • 5
  • 14
rmmariano
  • 896
  • 1
  • 18
  • 32
  • 1
    Can you explain me how you import a png into your code? Did you had to implement some specificity in the angular.json file, or somewhere else? – Raphaël Balet May 03 '21 at 07:56
  • I've imported the png on my code using the code above. I've added my png file inside `@/assets` folder, then I've imported it using `import variable from ` and I've added the `variable` inside `new Icon`. – rmmariano May 06 '21 at 15:22