Skip to content

Instantly share code, notes, and snippets.

@mateusjunges
Last active November 9, 2020 18:34
Show Gist options
  • Save mateusjunges/51bdbb2adc182b49baaf39f0ca197410 to your computer and use it in GitHub Desktop.
Save mateusjunges/51bdbb2adc182b49baaf39f0ca197410 to your computer and use it in GitHub Desktop.
Function to decode a polyline using php
/**
* Decodes path string into a sequence of LatLngs.
*
* @param string $encoded_path
* @param int $precision
* @return array
*/
public static function decode(string $encoded_path, int $precision = 6)
{
$len = strlen( $encoded_path ) -1;
// For speed we preallocate to an upper bound on the final length, then
// truncate the array before returning.
$path = [];
$index = 0;
$lat = 0;
$lng = 0;
while( $index < $len) {
$result = 1;
$shift = 0;
do {
$b = ord($encoded_path[$index++]) - 63 - 1;
$result += $b << $shift;
$shift += 5;
} while ($b >= hexdec("0x1f"));
$lat += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
$result = 1;
$shift = 0;
do {
$b = ord($encoded_path[$index++]) - 63 - 1;
$result += $b << $shift;
$shift += 5;
} while ($b >= hexdec("0x1f"));
$lng += ($result & 1) != 0 ? ~($result >> 1) : ($result >> 1);
array_push($path,
[
'lat' => $lat * 1 / pow(10, $precision),
'lng' => $lng * 1 / pow(10, $precision)
]
);
}
return $path;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment