Skip to content

Instantly share code, notes, and snippets.

@gpiffault
Created August 2, 2019 08:55
Show Gist options
  • Save gpiffault/95cd889eee159656c3019544a956c4c5 to your computer and use it in GitHub Desktop.
Save gpiffault/95cd889eee159656c3019544a956c4c5 to your computer and use it in GitHub Desktop.
Decode google encoded polyline
// https://developers.google.com/maps/documentation/utilities/polylinealgorithm
function polylineDecode (str, precision) {
// Decode str to int array
let strIndex = 0
let values = []
while (strIndex < str.length) {
let byte
let result = 0
let shift = 0
do {
byte = str.charCodeAt(strIndex++) - 63
result |= (byte & 0x1f) << shift
shift += 5
} while (byte >= 0x20)
values.push((result & 1) ? ~(result >> 1) : (result >> 1))
}
const factor = Math.pow(10, precision === undefined ? 5 : precision)
const dim = 2
let coords = []
// Deltas -> absolute values
for (let i = dim; i < values.length; i++) values[i] += values[i - dim]
// Group & scale
for (let i = 0; i < values.length; i += dim) coords.push(values.slice(i, i + dim).map(n => n / factor))
return coords
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment