简体   繁体   中英

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.

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?

在此处输入图片说明

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...

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM