Search code examples
openlayers

Tiling an image up into XYZ tiles


I cant find any specifications for the XYZ tiles source used by OpenLayers

I have some images where I for each know the 4 corners in the a Mercator projection (EPSG:3857)

I would like to tile those images into XYZ directories, but are not sure how I find the corners of each xyz tile at each zoom lvl. If I can calculate all the xyz tiles corners also in EPSG:3857 coordinates, I simply could cut out the intersection parts with the 4 corners of the images.


Solution

  • The general idea is that the earth is assumed to be spherical, with a circumference at the equator of 40,075 km. This in then divided in half in both North/South and East/West directions, converted into meters, which gives a top left starting point of (-20037508.34, 20037508.34). So, to find any tile you simply take the difference between the top left and your current point expressed in the meters of Spherical Mercator (EPSG:3857) and divide by the resolution times the tile size, ie, the number of meters covered by a tile at any zoom level.

    x = Math.round((bounds.left - maxExtent.left) / (resolution * tileSize.w));
    y = Math.round((maxExtent.top - bounds.top) /  (resolution * tileSize.h));
    

    These calculations can be seen in the getXYZ function here: OpenLayers.Layer.XYZ.js. For this to be clean, you probably don't want to deviate from the standard EPSG:3857 resolutions which are defined in the initMercatorProjection function here OpenLayers/Layer/SphericalMercator.js.

    There is an interesting page here, that shows various tile scheme calculations visually: http://www.maptiler.org/google-maps-coordinates-tile-bounds-projection/