Last active
July 15, 2023 05:06
-
-
Save thomaswilburn/806119e910960dc01c6137de43506ed3 to your computer and use it in GitHub Desktop.
Decoding function for Google's polyline encoded strings
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
/* | |
This is more complicated than it would normally be, because A) it delivers | |
output in pairs, and B) those pairs are all offsets from the previous pair. | |
If you're just delivering a stream of values, this is about 1/2 as long. | |
*/ | |
function decode(str) { | |
// last known coordinate for adding offsets | |
var from = [0, 0]; | |
var value = 0; | |
var shift = 0; | |
// lat/long pair and internal index | |
var pair = []; | |
var latLong = 0; | |
// final output | |
var output = []; | |
for (var char of str) { | |
// get the actual numerical value of the character | |
var code = char.charCodeAt(0) - 63; | |
// the data in the chunk is the rightmost 5 bits, the leftmost bit is a continuation flag | |
var byte = code & 31; | |
// add this to the value | |
value |= byte << shift; | |
shift += 5; | |
// if the leftmost bit was set, we're done with the assembled value | |
if (code < 32) { | |
// if it was negative, the rightmost bit will be set | |
// so shift and get the twos complement | |
if (value & 1) { | |
value = ~(value >> 1); | |
} else { | |
value = value >> 1; | |
} | |
// reduce by the scaling factor and add to the last known coordinate pair | |
value *= .00001; | |
pair[latLong] = from[latLong] + value; | |
value = 0; | |
shift = 0; | |
latLong++; | |
// once we're done with the pair, push it and reset | |
if (latLong == 2) { | |
latLong = 0; | |
from = pair; | |
output.push(pair); | |
pair = []; | |
} | |
} | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reverses the format (used in some Maps products) found here into lat/long pairs: https://developers.google.com/maps/documentation/utilities/polylinealgorithm Useful for scraping these into actual GIS coordinates.