I’m trying to write a script in PHP that will accept a Bing maps quadkey and then return the zoom level, x-coordinate and y-coordinate so that I can use my own maps. I’ve based my code off the C# example code provided by Microsoft as such here:
public static void QuadKeyToTileXY(string quadKey, out int tileX, out int tileY, out int levelOfDetail)
{
tileX = tileY = 0;
levelOfDetail = quadKey.Length;
for (int i = levelOfDetail; i > 0; i--)
{
int mask = 1 << (i - 1);
switch (quadKey[levelOfDetail - i])
{
case '0':
break;
case '1':
tileX |= mask;
break;
case '2':
tileY |= mask;
break;
case '3':
tileX |= mask;
tileY |= mask;
break;
default:
throw new ArgumentException("Invalid QuadKey digit sequence.");
}
}
}
This is my recreation using PHP that isn’t operating as I would expect:
$quadkey = intval($_GET["quadkey"]);
$zoom = count($quadkey);
for ($i = $zoom; $i > 0; $i--)
{
$mask = 1 << ($i - 1);
$quadkey_array = str_split($quadkey);
switch ($quadkey_array[$zoom - $i])
{
case 0:
break;
case 1:
$x |= $mask;
break;
case 2:
$y |= $mask;
break;
case 3:
$x |= $mask;
$y |= $mask;
break;
default:
echo "Error";
}
echo "/" . $zoom . "/" . $x . "/" . $y . ".png";
}
The example quadkey I’m using and the expected results are as follows:
Quadkey: 120202111102203112
X-coord: 134926
Y-coord: 86121
Zoom: 18
Would anyone be able to shed some light on what I’m doing wrong? I’ve been looking all around and can’t find any other example code to examine! Thanks all!
There are mistakes in my code that I should have seen.
Is wrong and counts the number of $quadkeys, not the length of the string.
Also, the URL should be generated outside of the for loop, just below it. I have placed the updated code below should anyone else need a PHP script for converting a Bing maps quadkey to coordinates.