# Python Geospatial Development Error

I'm working through some examples in the Python Geospatial Development book by Erik Westra.

On page 439, about setting up a tile map server, he gives the following code for calculating a bounding box based on a centre location and a zoom level:

``````TILE_WIDTH = 256
TILE_HEIGHT = 256

x_extent = _unitsPerPixel(zoomLevel) * TILE_WIDTH
y_extent = _unitsPerPixel(zoomLevel) * TILE_HEIGHT

min_long = x * x_extent - 180.0
min_lat = y * y_extent - 90.0
max_long = min_long + x_extent
max_lat = min_lat + y_extent

def _unitsPerPixel(zoomLevel):
return 0.703125/math.pow(2, zoomLevel)
``````

Nowhere does he specify what the `x` and `y` units are expected to be. I assumed lat long coords (same as map) but then the above calculations do not work.

For example, suppose I have `x = 50.0` and `y=-2.09` and a zoom level of 5.

For the min_lat, I will then have approximately:

``````min_lat = -2.09 * 5.63 - 90.0
``````

Which is going to give less than -90, the limit of our map...?!?

Everytime you pass a negative lat/long coordinate this will fall down....

Just what x/y coordinates are being expected here?

The values for `x` and `y` in this case are probably just indices for an X-Y-Z tilemap. The indices of a TMS service are unitless, they simply count the number of tiles from the top-left corner.

In your example, the `_unitsPerPixel` function returns the scale of the pixels for the given zoom level. The value is the width and height of one pixel in the units of the projection (which here appears to be lat/lon). When multiplied with the `TILE_WIDTH`, you get the scale of one tile in the units of the coordinates system you are working in.

With this, the value `x * x_extent - 180` (where `x` is the tile index) gives you a long value minus the "offset" of -180 degrees. The offset is necessary because you start counting from the left to the right. So if the index `x` is zero, you are on the left edge of the map and the `min_long` value is -180. So neither x nor y should assume a negative value.

Tile Map Servers are usually built for use on the web, where the library (such as OpenLayers or Leaflet) ask for a tile using only the xyz tile index, and not any spatial querying. For further reading on this see

http://en.wikipedia.org/wiki/Tiled_web_map

Here is a nice visualization of how tile indices work for google maps (note that there are other definitions as well)