Transforming a Pixel to a Map Coordinate

To pan or zoom a map based on tiles from the Map Tiling Service the client must have the ability to convert a pixel to a location on the Earth. To do this the client must create an affine transform that when given a coordinate in pixels returns a coordinate in the projection of the tiles. You need to know the projection of the tiles, the bounds of the map being tiled, and the dimensions of a tile. Given this information you must do the following:

  1. Calculate the maximum number of tiles across that represents the map.
  2. Calculate the maximum number of tiles down that represents the map.
  3. Calculate the maximum number of pixels across that represents the map.
  4. Calculate the maximum number of pixels down that represents the map.
  5. Create an affine transform based on the bounds of the map and the bounds of the map in pixels.
  6. Feed your location in pixels into the affine transform. The result will be a location on the earth in the projection of the map.

To perform these steps, and transform a pixel into your map's coordinate system:

  1. Calculate the maximum number of tiles across the map using the following equation: tilesAcross = 2level
  2. Calculate the maximum number of tiles down the map using the following equation: tilesDown = 2level
  3. Calculate the number of pixels across the entire map using the following equation: pixelsAcross = tileWidth × tileAcross
  4. Calculate the number of pixels down the entire map using the following equation: pixelsDown = tileHeight × tileDown
  5. Given the bounds of the map in the map's projection and the bounds of the map in pixels an affine transform from pixels to map coordinates can be constructed. The pixel coordinate passed must be in the map's pixel space. It may not be enough to directly feed a pixel coordinate from a mouse location on the screen. For instance, you may have to convert the mouse location to a location in the map's pixel space. This involves keeping track of the location in map pixels space of the upper right-hand corner of the image control and offsetting the mouse location with that location.