Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG icons in Leaflet.js map

I have a working Leaflet map but cannot pass in SVG icons using encodeURI (have not tried encodeURIComponent because I'm not sure that is the issue). The gist I'm using shows how to pass in SVG rectangles and this works:

<svg xmlns='http://www.w3.org/2000/svg'> <rect> x='0' y='0' width='20' height='10' fill='#000000' </rect> </svg> 

However, I cannot pass in a circle or a path successfully, even though the code is valid, optimized in SVGOMG, and appearing properly on SVG linters such as SVG Viewer. For example, a star.

<svg xmlns='http://www.w3.org/2000/svg' width='50px' height='50px'><path d='M2,111 h300 l-242.7,176.3 92.7,-285.3 92.7,285.3 z' fill='#000000'/></svg>

An example is on CodePen and the relevant lines of code are:

var svgicon ="<svg xmlns='http://www.w3.org/2000/svg' width='50px' height='50px'><path d='M2,111 h300 l-242.7,176.3 92.7,-285.3 92.7,285.3 z' fill='#000000'/></svg>"

var url = encodeURI("data:image/svg+xml," + svgicon).replace(/%20/g, ' ').replace(/%22/g, "'").replace(/%3C/g,'<').replace(/%3E/g,'>');
console.log(url);

You can see the SVG path in the console.

"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='50px' height='50px'><path d='M2,111 h300 l-242.7,176.3 92.7,-285.3 92.7,285.3 z' fill='#000000'/></svg>"

Nothing shows up and there is no error message. Sometimes, a broken image link shows up.

like image 433
achen Avatar asked Jul 14 '17 19:07

achen


1 Answers

Can you display that svg in a browser? I don't think the SVG path is well formed.

You define a 50(px) x 50(px) svg canvas.

<path d="
M2,111
h300
l-242.7,176.3
   92.7,-285.3
   92.7,285.3
Z
" fill="#000"/>

You start the path with an absolute (M)ove declaration at 2,111 which is outside of the canvas. Followed by a relative (h)orizontal line 300 to the right. Then relative (l)ines -242.7,176.3 92.7,-285.3 92.7,285.3 before you clo(Z)e the path.

If I set the canvas to 1000 * 1000 I see this icon in the browser. Is this what you would like to see?

enter image description here

I draw this in LeafletJS like so:

let achenSvgString = "<svg xmlns='http://www.w3.org/2000/svg' width='1000' height='1000'><path d='M2,111 h300 l-242.7,176.3 92.7,-285.3 92.7,285.3 z' fill='#000000'/></svg>"
let myIconUrl = encodeURI("data:image/svg+xml," + achenSvgString).replace('#','%23');

// L.icon({
//     iconUrl: myIconUrl,
//     iconSize: 40
// });

I didn't adjust the size as I just hammered this into a working bit of code but you can see the stars drawing here...

enter image description here

like image 89
Dennis Bauszus Avatar answered Oct 10 '22 06:10

Dennis Bauszus