Do you want to reduce redundancy for Google Maps marker images? Our Front-end Developer Robert Katzki found out how you could embed an SVG file into the Google Maps API.
For a Google Maps based project (the web version of Boschung RWIS app) with a lot of similar markers, I was looking for a way to reduce redundancy for these marker images. The marker images look all the same, only differing in the background color. Also there is a gradient and a drop shadow included. That would be a perfect use case for a SVG symbol sprite!
Sadly the Google Maps API doesn’t allow us to use a SVG sprite as a marker image. No matter what you try – the
<use> method or specifying an external file like
markers.svg#my-icon – the marker won’t show up on the map.
When I stumbled across Fun with SVG: Embedding in CSS, an article explaining how to embed an SVG file in CSS, I got interested. Will that work with the Maps API, too? Indeed – it does work!
anchor: new google.maps.Point(16, 16),
url: 'data:image/svg+xml;utf-8, \
<svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"> \
<path fill="red" stroke="white" stroke-width="1.5" d="M3.5 3.5h25v25h-25z" ></path> \
Notice that you can use line breaks, when you escape them.
Maps API doesn’t like special characters (
# especially), though. It doesn’t render the marker at all when that character is somewhere in the SVG. Defining a dropshadow via url (
#dropshadow) does not work initially. Trick is, to use
encodeURIComponent to escape all these characters.
This article first appeared here: robert.katzki.de/posts/inline-svg-as-google-maps-marker
Learn more about the usage of Google Maps API