[GIS] Formula of mapnik bounding box (spherical mercator)

extentsmapnikmercator

I want to implement a tile server and I'm following the code in the repo node-mapnik-sample-code.

When a request is sent with the parameters x, y, z (longitude, latitude, zoom), those parameters are used to create a bounding-box, with the following code:

/**
 * Convert tile xyz value to Mapnik envelope
 *
 * @param {Number} x latitude number.
 * @param {Number} y longitude number.
 * @param {Number} zoom zoom.
 * @param {Boolean} tms_style whether to compute a tms tile.
 * @return Object Mapnik envelope.
 */
SphericalMercator.prototype.xyz_to_envelope = function(x, y, zoom, TMS_SCHEME) {
    if (TMS_SCHEME) {
        y = (Math.pow(2, zoom) - 1) - y;
    }
    var ll = [x * this.size, (y + 1) * this.size];
    var ur = [(x + 1) * this.size, y * this.size];
    var bbox = this.px_to_ll(ll, zoom).concat(this.px_to_ll(ur, zoom));
    return mercator.forward(bbox);
};

(full code here: https://github.com/mapnik/node-mapnik-sample-code/blob/master/utils/sphericalmercator.js)

Why the longitude and latitude have to be multiplied by the tile size (256) here:

var ll = [x * this.size, (y + 1) * this.size];

I'm getting lost between pixels and geographic coordinates.

Best Answer

The x and y parameters to that function are tile coordinates, where the x and y values represent the number of tiles from the top-left corner of the map in each direction. In Google's numbering system, the tile coordinates start at (0, 0) for the top-left tile.

var ll = [x * this.size, (y + 1) * this.size];

The line above that you've highlighted is calculating the pixel coordinates for the lower-left corner of the tile. For example, if the tile coordinates (x and y parameters to the function) are (2,3), and tile size is 256, the lower left corner of that tile would be at (2 * 256, (3 + 1) * 256) = (512, 1024).

I found this maptiler.org page on Google maps coordinates particularly helpful to visualise the system. Below is a screenshot from that page, showing the tile system at zoom level 1.

Google maps tile coordinates at zoom level 1