Skip to content

Instantly share code, notes, and snippets.

@amitzur
Last active September 6, 2017 14:02
Show Gist options
  • Save amitzur/22886819aacce0d1f3861fbea653e0e0 to your computer and use it in GitHub Desktop.
Save amitzur/22886819aacce0d1f3861fbea653e0e0 to your computer and use it in GitHub Desktop.
Function to transform svg path

What?

You got an SVG path like M20,20 30,20 30,30 20,30 Z, which is a 10x10 square whose top left corner is positioned at 20,20. You would like that square's top left corner to be positioned at 0,0.

Why?

See here: https://developers.google.com/maps/documentation/javascript/symbols#add_to_marker

Google maps API allows to specify a path as a marker. This allows to do cool stuff like theming of the marker, which is the reason I needed to do this whole thing. The challenge here is that the exact location of the marker is mapped to the SVG path's 0,0. So if you have an SVG of a custom pin, like the one attached to this gist, you have to make sure that the pointy part of the pin is located at 0,0.

And that's what this function does.

Display the source blob
Display the rendered blob
Raw
<?xml version="1.0" encoding="UTF-8"?>
<svg width="20px" height="27px" viewBox="0 0 20 27" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch -->
<title>Artboard</title>
<desc>Created with Sketch.</desc>
<defs></defs>
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Artboard" stroke-width="1.5" stroke="#FFFFFF" fill="#6AC1FF" fill-rule="nonzero">
<g id="map_pin_default">
<path d="M9.99931,0 C4.476879,0 0,4.4759483 0,9.9993103 C0,17.2725517 9.4365,27 10.287931,27 C11.135172,27 20.000017,16.4155345 20.000017,9.9993103 C19.999552,4.4759483 15.522672,0 9.99931,0 L9.99931,0 Z M9.951828,13.3417241 C7.784379,13.3417241 6.028448,11.6328103 6.028448,9.5230862 C6.028448,7.4147586 7.783914,5.7039828 9.951828,5.7039828 C12.119741,5.7039828 13.876138,7.4147586 13.876138,9.5230862 C13.876138,11.6328103 12.119741,13.3417241 9.951828,13.3417241 L9.951828,13.3417241 Z" id="pin"></path>
</g>
</g>
</g>
</svg>
function translatePath(path, offsetX, offsetY) {
return path.split(" ").map(p => {
const arr = p.split(",");
if (arr.length !== 2) return p;
let c;
if (isNaN(arr[0][0])) {
c = arr[0][0];
arr[0] = arr[0].slice(1);
}
arr[0] = Number(arr[0]) + offsetX;
arr[1] = Number(arr[1]) + offsetY;
return `${c || ""}${arr}`;
}).join(" ")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment