Created
August 2, 2019 08:55
-
-
Save gpiffault/95cd889eee159656c3019544a956c4c5 to your computer and use it in GitHub Desktop.
Decode google encoded polyline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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