How can I use an SVG image as a map marker in OpenLayers-3?

为君一笑 提交于 2019-11-30 09:22:19

Based on @ahocevar answer, you can use data URIs for SVG:

new ol.style.Style({
  image: new ol.style.Icon({
    anchor: [0, 0],
    src: 'data:image/svg+xml;utf8,<svg>/* SVG DATA */</svg>'
  })
});

SVG icons work fine as long as the content-type of your SVG image file is image/svg+xml. Also note that no external references are supported inside the SVG. OpenLayers 3 simply uses the drawImage function of the 2d context. You can find more details on the requirements of SVG content here: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Drawing_DOM_objects_into_a_canvas.

Convert the SVG to Base 64 . This (Link) helped me.

copied the base 64 and used it as a string in javascript .

Eg : var svg = "convertedBase64";

Then

var icon = new ol.style.Icon({
        src:'data:image/svg+xml;base64,'+svg ,
        other props
});

And you are done, may be a few Kbs more than SVG but this did work perfect for me .

I had the same issue, but not even serving the image with the proper mime type helped.

It boiled down to the SVG not defining width and height properly.

I added the width and height attributes to the <svg> tag, like:

<svg width="100px" height="100px" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0.75 0 30 45" xml:space="preserve">

After that I was able to use my svg just like any other image.

I also had issues to show the icon image, ahocevar answer helped me to solve my problem but I had also to search for the php header, for SVG In case you are or others who see this answer are using php to generate the SVG you have to use header function to identify the content-type

header('Content-type: image/svg+xml'); /* this line will do the magic */
echo '<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
</svg>';

Building upon SoonDead's answer, I had to come up with a way to add the width and height to the svg without touching the source. Using angular, this is sort of what I did:

$http.get('path/to/image.svg').then(function (response) {
  // create element
  var svgEl = angular.element(response.data);

  // set width and height
  svgEl.attr('width', '50px');
  svgEl.attr('height', '50px');

  // base64 encode
  var base64Svg = btoa(unescape(encodeURIComponent(svgEl[0].outerHTML)));

  // create the style
  var style = new ol.style.Style({
    image: new ol.style.Icon({
      src: 'data:image/svg+xml;base64,'+base64Svg,
      imgSize: [50, 50],
      size: [50, 50],
    })
  });

 // apply the style
 feature.setStyle(style);
});

It's a little verbose, but it seems to do the job.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!