Make Points transformable.

This commit is contained in:
Marc Jansen
2012-06-20 14:58:37 +02:00
parent 33c2e0aa30
commit d933404df8
2 changed files with 72 additions and 1 deletions

View File

@@ -106,3 +106,37 @@ ol.geom.Point.prototype.setZ = function(z) {
this.z_ = z;
};
/**
* Transform this point to another coordinate reference system. This
* requires that this point has a projection set already (if not, an error
* will be thrown). Returns a new point object and does not modify this
* point.
*
* @param {string|!ol.Projection} proj The destination projection. Can be
* supplied as a projection instance of a string identifier.
* @returns {!ol.geom.Point} A new location.
*/
ol.geom.Point.prototype.transform = function(proj) {
if (goog.isString(proj)) {
proj = new ol.Projection(proj);
}
return this.transform_(proj);
};
/**
* Transform this point to a new location given a projection object.
*
* @param {!ol.Projection} proj The destination projection.
* @returns {!ol.geom.Point}
* @private
*/
ol.geom.Point.prototype.transform_ = function(proj) {
var point = {x: this.x_, y: this.y_};
var sourceProj = this.projection_;
if (!goog.isDefAndNotNull(sourceProj)) {
throw new Error("Cannot transform a point without a source projection.");
}
ol.Projection.transform(point, sourceProj, proj);
return new ol.geom.Point(point.x, point.y, this.z_, proj);
};

View File

@@ -2,7 +2,6 @@ describe("ol.geom.Point", function() {
var p2Args,
p3Args,
p4Args,
p_arr,
proj = "EPSG:4326";
var instances = {
@@ -57,6 +56,7 @@ describe("ol.geom.Point", function() {
expect(instance.getProjection).not.toBeUndefined();
expect(instance.setProjection).not.toBeUndefined();
});
}
}
@@ -83,4 +83,41 @@ describe("ol.geom.Point", function() {
expect(p4Args.getProjection()).not.toBeNull();
expect(p4Args.getProjection()).toBeA(ol.Projection);
});
it("can be transformed", function(){
// save for later comparison
var old = {
x: p4Args.getX().toFixed(3),
y: p4Args.getY().toFixed(3)
};
// with code only
var transformedPoint = p4Args.transform("EPSG:3857");
// is it still an instance of ol.geom.Point?
expect(transformedPoint).toBeA(ol.geom.Point);
// coordinates OK?
expect(transformedPoint.getX().toFixed(3)).toBe("2337709.306");
expect(transformedPoint.getY().toFixed(3)).toBe("445640.110");
// with an ol.Projection
var retransformedPoint = transformedPoint.transform(new ol.Projection("EPSG:4326"));
expect(retransformedPoint).toBeA(ol.geom.Point);
// coordinates shopulkd be the originally configured
expect(retransformedPoint.getX().toFixed(3)).toBe(old.x);
expect(retransformedPoint.getY().toFixed(3)).toBe(old.y);
});
it("throws an exception when you try to transform without a source projection", function(){
expect(function() {
p2Args.transform("EPSG:3857");
}).toThrow();
expect(function() {
p3Args.transform("EPSG:3857");
}).toThrow();
});
});