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