Last active
November 9, 2020 18:34
-
-
Save mateusjunges/51bdbb2adc182b49baaf39f0ca197410 to your computer and use it in GitHub Desktop.
Function to decode a polyline using php
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
/** | |
* 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