Skip to content

Instantly share code, notes, and snippets.

@andrewn
Created February 9, 2010 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewn/299261 to your computer and use it in GitHub Desktop.
Save andrewn/299261 to your computer and use it in GitHub Desktop.
var mapBounds = new OpenLayers.Bounds( -20037508.34, -20037508.34,
20037508.34, 20037508.34);
/*
Converts TMS tile coordinates to Microsoft QuadTree.
*/
function tmsToQuadTree(/* int */ tx, /* int */ ty, /* int */ zoom) {
var quadKey = [];
// ISSUE: When using VirtualEarth or Google, need to put a '0' before the quadkey
// to compensate for those providers zoom level being reported as 0.
// When using CloudMade, the 0 is correctly calculated.
if( typeof window.QUADKEY_INITIAL_HACK == "number" ) {
quadKey.push( window.QUADKEY_INITIAL_HACK );
}
ty = ( Math.pow(2, zoom) - 1 ) - ty;
for (var i = zoom; i > 0; i--) {
var digit = 0;
var mask = 1 << (i - 1);
if ((tx & mask) != 0)
digit += 1;
if ((ty & mask) != 0)
digit += 2;
quadKey.push(digit);
}
return quadKey.join("");
}
/*
Given a bounds object, return the
full URL path to the tile using the
Microsoft Quadtree organisation.
*/
function getQuadTreeURL( bounds, layer ) {
var tms = getTMS( bounds, layer ),
quadKey = tmsToQuadTree( tms.x, tms.y, tms.z ),
// layer.type -> 'png'
path = quadKey + "." + layer.type,
// layer.url -> '/haiti/tiles/'
url = layer.url + path;
return url;
}
/*
Return x, y, z position for a tile
using the TMS specification.
*/
function getTMS( bounds, layer ) {
bounds = layer.adjustBounds(bounds);
var res = layer.map.getResolution(),
x = Math.round((bounds.left - layer.tileOrigin.lon) / (res * layer.tileSize.w)),
y = Math.round((bounds.bottom - layer.tileOrigin.lat) / (res * layer.tileSize.h)),
z = layer.map.getZoom();
return { x:x, y:y, z:z };
}
/*
Given a bounds object and map layer, return the full URL
path for the tile using the TMS specification.
*/
function getTMSURL( bounds, layer ) {
var tms = getTMS( bounds, layer );
var path = layer.serviceVersion + "/" + layer.layername + "/" + tms.z + "/" + tms.x + "/" + tms.y + "." + layer.type;
var url = layer.url;
if ( mapBounds.intersectsBounds( bounds ) && tms.z >= mapMinZoom && tms.z <= mapMaxZoom) {
return layer.url + path;
} else {
return "http://localhost/none.png";
}
}
/*
This is passed to an instance of OpenLayers.Layer.TMS
to provide a URL for a single tile.
*/
function getURL( bounds ) {
//var url = getTMSURL( bounds, this );
var url = getQuadTreeURL( bounds, this );
return url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment