This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Convert Latitude and Longitude to Tile Y and Tile X

Tags: None
(comma "," separated)
Beacon11
Registered Member
Posts
35
Karma
0
Hello. I have a tool that generates map tiles given a map image, latitude and longitude of the bottom left corner, and map width and height in meters. In order to determine which tiles need to be generated, I convert lats/lons to tiles by using the formulas provided here: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames . I'll paste them in for reference.

Code: Select all
int long2tilex(double lon, int z)
{
   return (int)(floor((lon + 180.0) / 360.0 * pow(2.0, z)));
}
 
int lat2tiley(double lat, int z)
{
   return (int)(floor((1.0 - log( tan(lat * M_PI/180.0) + 1.0 / cos(lat * M_PI/180.0)) / M_PI) / 2.0 * pow(2.0, z)));
}
 
double tilex2long(int x, int z)
{
   return x / pow(2.0, z) * 360.0 - 180;
}
 
double tiley2lat(int y, int z)
{
   double n = M_PI - 2.0 * M_PI * y / pow(2.0, z);
   return 180.0 / M_PI * atan(0.5 * (exp(n) - exp(-n)));
}


Note that all examples in this post use a zoom level of 18.

The only problem is: while longitudes seem to work, the latitude functions don't! For instance: it claims that the tile Y containing the latitude of 0 is 131072, which is correct; 131072's NW corner is indeed at a latitude of 0. However, it also claims the NW corner of tile Y 131071 is 0.00137329 degrees, which is incorrect! It's actually 0.000694 degrees. That trend continues-- latitudes always seem to be multiplied by two when tiley2lat() is used, etc. Does anyone know what's wrong? Does Marble have a different/better way of doing these calculations?
Beacon11
Registered Member
Posts
35
Karma
0
I see some code that MIGHT do what I'm looking for... but it goes way over my head. I'm talking about TileScalingTextureMapper::mapTexture(). It seems to load tiles corresponding to the viewport center, but I don't quite understand the logic it uses to turn those lats/lons into tile IDs. It doesn't look like there are simple functions to do this, huh?
User avatar
tackat
KDE Developer
Posts
131
Karma
0
OS
No, mapTexture is rather about triggering and doing the texture mapping.

I think

TileId TileId::fromCoordinates(const GeoDataCoordinates &coords, int zoomLevel)

is a bit more about what you are after. The only thing I wonder about is why it doesn't take the source projection into account (Mercator vs. Equirect).


Bookmarks



Who is online

Registered users: Bing [Bot], claydoh, Google [Bot], rblackwell