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
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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