Add ol.TileCoord.toQuadKey and createFromQuadKey

This commit is contained in:
Tom Payne
2012-07-25 17:39:38 +02:00
parent 3ddb1137cc
commit 7902803063
2 changed files with 73 additions and 0 deletions

View File

@@ -4,6 +4,17 @@ goog.require('goog.array');
goog.require('ol.Coordinate');
/**
* @enum {number}
*/
ol.QuadKeyCharCode = {
ZERO: '0'.charCodeAt(0),
ONE: '1'.charCodeAt(0),
TWO: '2'.charCodeAt(0),
THREE: '3'.charCodeAt(0)
};
/**
* @constructor
@@ -25,6 +36,33 @@ ol.TileCoord = function(z, x, y) {
goog.inherits(ol.TileCoord, ol.Coordinate);
/**
* @param {string} quadKey Quad key.
* @return {ol.TileCoord} Tile coordinate.
*/
ol.TileCoord.createFromQuadKey = function(quadKey) {
var z = quadKey.length, x = 0, y = 0;
var mask = 1 << (z - 1);
var i;
for (i = 0; i < z; ++i) {
switch (quadKey.charCodeAt(i)) {
case ol.QuadKeyCharCode.ONE:
x += mask;
break;
case ol.QuadKeyCharCode.TWO:
y += mask;
break;
case ol.QuadKeyCharCode.THREE:
x += mask;
y += mask;
break;
}
mask >>= 1;
}
return new ol.TileCoord(z, x, y);
};
/**
* @return {ol.TileCoord} Clone.
*/
@@ -41,6 +79,28 @@ ol.TileCoord.prototype.hash = function() {
};
/**
* @return {string} Quad key.
*/
ol.TileCoord.prototype.toQuadKey = function() {
var digits = new Array(this.z);
var mask = 1 << (this.z - 1);
var i, charCode;
for (i = 0; i < this.z; ++i) {
charCode = ol.QuadKeyCharCode.ZERO;
if (this.x & mask) {
charCode += 1;
}
if (this.y & mask) {
charCode += 2;
}
digits[i] = String.fromCharCode(charCode);
mask >>= 1;
}
return digits.join('');
};
/**
* @return {string} String.
*/

View File

@@ -2,6 +2,14 @@ goog.require('goog.testing.jsunit');
goog.require('ol.TileCoord');
function testCreateFromQuadKey() {
var tileCoord = ol.TileCoord.createFromQuadKey('213');
assertEquals(3, tileCoord.z);
assertEquals(3, tileCoord.x);
assertEquals(5, tileCoord.y);
}
function testConstructorOrderZXY() {
var tc1 = new ol.TileCoord(1, 2, 3);
assertEquals(1, tc1.z);
@@ -24,3 +32,8 @@ function testFromString() {
assertEquals(2, tc.x);
assertEquals(3, tc.y);
}
function testToQuadKey() {
assertEquals('213', (new ol.TileCoord(3, 3, 5)).toQuadKey());
}