I tried converting lat/long to XYZ tile and again using the XYZ values trying to get back the lat/long. The values of lat/long are not the same (the original one and the converted one). I referred to https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#C.23 and got the formula for conversion.
Below is the code for your reference:
Converting from lat/long to XYZ:
var x = (int)Math.Floor((longitude 180.0) / 360.0 * Math.Pow(2, zoom));
var y = (int)Math.Floor((1 - Math.Log(Math.Tan((Math.PI / 180) * latitude) 1 / Math.Cos((Math.PI / 180) * latitude)) / Math.PI) / 2 * Math.Pow(2, zoom));
Converting from XYZ to lat/long:
var longitude = x / Math.Pow(2, z) * 360 - 180;
var n = Math.PI - 2 * Math.PI * y / Math.Pow(2, z);
var latitude = 180 / Math.PI * Math.Atan(0.5 * (Math.Exp(n) - Math.Exp(-n)));
When I pass latitude = -477.42187500000006, longitude = 37.3002752813443, zoom = 15, then I get x = 19779 and y = -2147483648.
But when I pass x = 19779, y = -2147483648, z = 15, then I get latitude = 90.0 and longitude = 37.298583984375 which is wrong.
I am not sure why the second conversion is giving the wrong results. Any help is highly appreciated.
CodePudding user response:
Latitudes are by definition belong to range -90 (south pole) to 90 (north pole).
So you start with invalid one -477.421875 and the result can be arbitrary.
The longitude is correct. It is slightly different from original, which is expected since you truncate x to nearest integer. If you want the same value, don't round to integer.
CodePudding user response:
The formulas mentioned in the question are correct and work fine. I was providing lat/long values in the wrong order.
As pointed out by @Michael, latitudes by definition belong to the range -90 (south pole) to 90 (north pole)
. I was passing latitude as -477.42187500000006 which is wrong.
I switched the values and passed latitude = 37.3002752813443, longitude = -477.42187500000006, then it worked. The values of lat/long are now coming the same (the original one and the converted one).