javascripthtmlsvgfont-awesomeopenlayers

Fontawesome svg-icons in openlayers


I know similar questions have been asked before but their answers don't help me. I'm trying to use Fontawesome-Icons as markers in an Openlayers map like this:

const svg = `
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.-->
                <path d="M320 64c0-12.6-7.4-24-18.9-29.2s-25-3.1-34.4 5.3L131.8 160H64c-35.3 0-64 28.7-64 64v64c0 35.3 28.7 64 64 64h67.8L266.7 471.9c9.4 8.4 22.9 10.4 34.4 5.3S320 460.6 320 448V64z"/></svg>
            `;
const svgUrl = 'data:image/svg+xml;charset=utf-8,' + svg;
let measurePointStyle = new ol.style.Style({
    image: new ol.style.Icon({              
        src: svgUrl,
        scale: 1
    }),
    text: new ol.style.Text({
        text: "IO",
        offsetY: 25,
        fill: new ol.style.Fill({
            color: '#000'
        }),
        stroke: new ol.style.Stroke({
            color: '#fff',
            width: 2
        })
    })
});

the text part of the style appears on the map correctly but the Icon does not. No errors. I've been looking for a solution for over an hour now but can't find anything that helps. If someone could tell me what I'm doing wrong here it would be highly appreciated.


Solution

  • The simplest solution is to use the JavaScript encodeURIComponent method:

    const svg = `
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--!Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.-->
                    <path d="M320 64c0-12.6-7.4-24-18.9-29.2s-25-3.1-34.4 5.3L131.8 160H64c-35.3 0-64 28.7-64 64v64c0 35.3 28.7 64 64 64h67.8L266.7 471.9c9.4 8.4 22.9 10.4 34.4 5.3S320 460.6 320 448V64z"/></svg>
                `;
    const svgUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
    let measurePointStyle = new ol.style.Style({
        image: new ol.style.Icon({              
            src: svgUrl,
            scale: 1
        }),
        text: new ol.style.Text({
            text: "IO",
            offsetY: 25,
            fill: new ol.style.Fill({
                color: '#000'
            }),
            stroke: new ol.style.Stroke({
                color: '#fff',
                width: 2
            })
        })
    });