I've been Slippy Tiles Wiki page for equations to convert lat/long values (given via the user) to tile references, and then work with the data relating to the tile.
My problem is the wiki's equation always does one of the following:
Returns a location 20+ miles away from my given lat/long. The range is ~18 miles to 200+ miles, no consistency.
Returns absolutely nothing, and the tile_row value (XXXXX) is always off by a considerable amount. This ranges from 40 (10810 instead of 10850) to 300+ (10417 in stead of 10817).
This happens for all lat longs, sourced from varying online mapping tools. So far I've tested this with Google Maps, OSM's own browsing tool and used lat/long generation tools for random locations across the UK.
Here's my code so far:
public void UserQuery()
{
Console.Write("Please enter a latitude value: ");
double userLat = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter a longitude value: ");
double userLong = Convert.ToDouble(Console.ReadLine());
_merc.TileLat = Math.Floor((1.0 - Math.Log(Math.Tan(DegreesToRadians(userLat)) + 1.0 / Math.Cos(DegreesToRadians(userLat))) / Math.PI) * (1 << ZoomLevel));
_merc.TileLong = Math.Floor((userLong + 180.0) / 360.0 * (1 << ZoomLevel));
}
private double DegreesToRadians(double angle)
{
return Math.PI * angle / 180;
}
The longitude value works perfectly everytime, it's just in there for reference.
The wiki's version of the equation is:
((1.0 - Math.Log(Math.Tan(lat * Math.PI / 180.0) +
1.0 / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom));
but my problem is that the last / 2
before bitshifting returns a value half of what's generally expected, so 5308
instead of 10616
. In terms of changes made to the equation, that's the only difference. I created a small method to work out radians => degrees because the original was hard to read and track (problems with brackets).