Use SVG icon as marker in OpenLayers
Asked Answered
P

3

19

I tried to svg icon as marker in Openlayers-3. Here in my code.

var svg = '<?xml version="1.0"?>'
            + '<svg viewBox="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg">'
            + '<circle cx="60" cy="60" r="60"/>'
            + '</svg>';

var style = new ol.style.Style({
            image: new ol.style.Icon({
                opacity: 1,
                src: 'data:image/svg+xml;base64,' + btoa(svg)
            })
        });

But my svg image is truncated,as shown in the following picture. ( the icon should be a circle)

enter image description here

Proudlove answered 15/6, 2016 at 8:25 Comment(0)
J
27

Here is an example that shows inline SVG in an icon symbolizer: http://jsfiddle.net/eze84su3/

Here is the relevant code:

var svg = '<svg width="120" height="120" version="1.1" xmlns="http://www.w3.org/2000/svg">'
    + '<circle cx="60" cy="60" r="60"/>'
    + '</svg>';

var style = new ol.style.Style({
  image: new ol.style.Icon({
    opacity: 1,
    src: 'data:image/svg+xml;utf8,' + svg,
    scale: 0.3
  })
});

A few differences from yours:

  • I added width and height attributes to the <svg>. This lets the browser know how big to make the resulting image.
  • I added a scale property to the icon to resize the image.
  • I used utf8 instead of base64 encoding (not significant).
Jo answered 17/6, 2016 at 4:41 Comment(2)
Thanks for the answer. But why viewBox parameter is not working?Proudlove
This works, but does have a couple of caveats because browsers tend to have issues with some of the characters used in SVG, like the double quotes, newlines, and spaces. I found it more reliable to first convert the SVG to Base64 (using window.btoa) and then including it as data:image/svg+xml;base64, followed by your base 64 encoded image.Goddord
S
4

To me, the solution was:

const iconMarkerStyle = new ol.style.Icon({
    src: './data/static_images/marker.svg',
    //size: [100, 100],
    offset: [0, 0],
    opacity: 1,
    scale: 0.35,
    //color: [10, 98, 240, 1]
})

Then add size parameters directly in the SVG file:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 144.81 215.81" width="14.5px" height="21.6px">
    <title>Asset 190-SVG</title>
</svg>
Sharpshooter answered 7/7, 2020 at 16:31 Comment(0)
P
0

I am using svg icon as image src in open layer styles.

var custstyle = new ol.style.Style({
 image: new ol.style.Icon({
    anchor: [0.5, 50],
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    src: './Icon.svg',
  }),
});
Pinckney answered 31/12, 2021 at 6:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.