Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active August 16, 2023 09:47
Show Gist options
  • Save clhenrick/6791bb9040a174cd93573f85028e97af to your computer and use it in GitHub Desktop.
Save clhenrick/6791bb9040a174cd93573f85028e97af to your computer and use it in GitHub Desktop.
Data URI SVG icons with Leaflet
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([30, 0], 2);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
var CustomIcon = L.Icon.extend({
options: {
iconSize: [40, 40],
shadowSize: [50, 64],
iconAnchor: [22, 94],
shadowAnchor: [4, 62],
popupAnchor: [-3, -76]
}
});
var svgrect = "<svg xmlns='http://www.w3.org/2000/svg'><rect x='0' y='0' width='20' height='10' fill='#5a7cd2'></rect><rect x='0' y='15' width='20' height='10' fill='#5d52cf'></rect></svg>";
/*
For data URI SVG support in Firefox & IE it's necessary to URI encode the string
& replace the '#' character with '%23'. `encodeURI()` won't do this which is
why `replace()` must be used on the string afterwards.
*/
var url = encodeURI("data:image/svg+xml," + svgrect).replace('#','%23');
console.log(url);
var rectIcon = new CustomIcon({iconUrl: url})
L.marker([52, -0.09], {icon: rectIcon}).bindPopup("I am data URI SVG icon.").addTo(map);
</script>
</body>
@adelaide01
Copy link

@chris I appreciate your example. However, I can only pass in SVG rectangles, but not circles or paths. I just posted a question in StackOverflow about it. Do you know the answer? https://stackoverflow.com/questions/45110081/svg-icons-in-leaflet-js-map

@dbauszus-glx
Copy link

@clhenrick That's brilliant. Thanks a lot mate. I was pooping around with creating dom objects from my xml string. Didn't even think about encoded URI. Works a treat.

@adelaide01 You can pass anything into icon url used in the LeafletJS icon object. Let me answer your stackoverflow question. I am sure somebody else would have already solved this if posted in the gis stackexchange where all the LeafletJS cracks hang out.

let mySvgString = '<svg width="866" height="1000" xmlns="http://www.w3.org/2000/svg"><metadata id="metadata1">image/svg+xml</metadata><circle fill="#fee08b" cx="466" cy="532" r="395"/><circle fill="#ffffbf" cx="400" cy="468" r="395"/></svg>'
let myIconUrl = encodeURI("data:image/svg+xml," + mySvgString).replace('#','%23');

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

This is what I use to create maps like this:

image

@adelaide01
Copy link

@dbauszus-glx Perfect! Thanks for taking the time. I'll accept your answer on StackOverflow and consider gis stackexchange in the future for Leaflet related questions.

@stefanolaru
Copy link

Thanks a lot for taking the time document this gist. While dabbling around I came across another way to use inline SVG as a marker, using L.divIcon, maybe it helps someone:

L.divIcon({ html: $(marker_svg)[0].outerHTML, // svgrect iconSize: [24, 38], iconAnchor: [12, 38] })

@hzitoun
Copy link

hzitoun commented Jan 29, 2018

Thanks man! That works perfectly!

@bmm
Copy link

bmm commented Oct 10, 2018

Thank you, it was very useful.
I had more than one #, so the replacement is like: .replace(new RegExp('#', 'g'),'%23').

@oswee
Copy link

oswee commented Dec 13, 2018

How apply some external styles like :hover un such URI encoded svg? Can't find any solutions except css filter which is too basic. Let's say i want to pass data into my svg like this:

let svgicon = `<svg id='marker` + markers[i][4] + `' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'>
    <defs>
          <style>
            .cls-1 {
              fill: #006aff;
            }      
            .cls-2 {
              font-size: 28px;
              fill: #fff;
              font-family: Montserrat-Regular, Montserrat;
            }
        </style>
    </defs>
    <path class="cls-1" d="M56.9679,24.9679A24.9679,24.9679,0,1,0,12.38928,40.42236h-.00067l18.4848,22.96552a1.38676,1.38676,0,0,0,2.22162.10583l17.86951-22.285H50.963A24.86853,24.86853,0,0,0,56.9679,24.9679Z"/>
    <text id='label` + markers[i][4] + `' class='cls-2' transform='translate(32 34)' text-anchor='middle'>` + markers[i][1] + `</text>
</svg>`

See that + markers[i][1] + in <text> tag...? This is important for me to pass some information to marker itself.
Then i encode it let url = encodeURI('data:image/svg+xml;utf8,' + svgicon).replace('#','%23'); ... and then all the rest stuff.
So... next thing is... i want to apply some custom styling for stroke, fill and the rest properties, when user hovers on this icon. Or if some events happen.
Have anybody any ideas?
I can't use there <svg><use xlink:href="file.svg#my-icon"> coz' i don't see a way to inject my dynamic text. Otherwise there would no be a problem to style it.
Swapping different styled svg icons ... is kind a solution, but i do not prefer it.

@rodrigodagostino
Copy link

I found your approach much more useful, @stefanolaru . Thanks a lot for sharing :)

@mgmskumara
Copy link

@stefanolaru it worked to me. Thanks

@DynamicArray
Copy link

Thanks for the code. For others reading this, I found the following works better (for me at least) than encodeURI:

var url = "data:image/svg+xml," + encodeURIComponent(svg);

This allow double-quotes in the SVG and no need to do the additional replace on hashes.

@JLuc
Copy link

JLuc commented Feb 6, 2021

Thanks @DynamicArray. var url = "data:image/svg+xml," + encodeURIComponent(svg); is the only code that worked for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment