Search code examples
openlayersopenlayers-6

How to apply a different icon into a cloned feature


I've implemented a feature which drawn an icon rather than a regular shape, as we can see in the picture below:

enter image description here

My intention is to add an icon alert beside this feature (and many others features). So, to try achieve this I'm cloning the feature and trying to apply a different image in the style being created, like the code below:

export const setIconEffect = (feature: Feature, event: any) => {
    const vectorContext = getVectorContext(event);

    // clone the feature geometry
    const flashGeom = feature.getGeometry().clone();

    // creates a new style to be applied into this cloned feature
    const style = new Style({
        image: new Icon({
            src: 'assets/images/mapElements/warning-icon.png',
            scale: 0.1,
            imgSize: toSize(500),
            anchorOrigin: IconOrigin.BOTTOM_RIGHT,
            anchor: [1.8, 0.05],
        }),
    });
    // set it into the cloned geometry
    vectorContext.setStyle(style);
    vectorContext.drawGeometry(flashGeom);
};

The problem is that, when I try to apply a different src, it doesn't work, but, if I use the same src it does work.

Applying a different src it just show the mark as usual. Applying the same src it draws the icon properly, but, as copy (and this is not the purpose). Example below:

enter image description here


Solution

  • After defining the style, we need to force the loading of the image by doing this:

    style.getImage().load();