JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.16.0/ol-debug.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.16.0/ol.css">
<div id="map" class="map"></div>
<div id="icon"></div>
CSS
svg {
width: 40px;
}
#map {
background-color: #999999;
}
JavaScript
var features = [];
var feature, geometry;
// Non-SVG icon. Displays fine.
geometry = new ol.geom.Point([500000, 0]);
feature = new ol.Feature(geometry);
feature.setStyle(
new ol.style.Style({
image: new ol.style.Circle({
radius: 15,
fill: new ol.style.Fill({
color: 'rgba(255, 153, 0, 1)'
})
})
})
);
features.push(feature);
geometry = new ol.geom.Point([0, 0]);
feature = new ol.Feature(geometry);
//not working svg
var svg2 = '<svg viewBox="-20 -20 40 40" xmlns="http://www.w3.org/2000/svg">' + '<polygon points="-10,10,10,10,10,-10,-10,-10,-10,10" fill="#000000"/></svg>';
// "good" svg
svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect fill="#00B1FF" width="100" height="100"/></svg>'
const img = document.createElement('IMG')
img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg)
const imgSize = [img.naturalWidth, img.naturalHeight]
console.log("after set", img, imgSize)
feature.setStyle(
new ol.style.Style({
image: new ol.style.Icon({
img: img,
imgSize: imgSize,
scale: 0.2
})
})
);
features.push(feature);
var vectorSource = new ol.source.Vector({
features: features
});
var vector = new ol.layer.Vector({
source: vectorSource
});
var map = new ol.Map({
layers: [vector],
target: document.getElementById('map'),
view: new ol.View({
center: [0, 0],
zoom: 4
})
});
// Render SVG in DOM as sanity check
document.getElementById('icon').innerHTML = svg;