From 0b5f0d0c8e19c8594c21d51777412b94550c1506 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Tue, 18 Mar 2014 15:12:59 +0100 Subject: [PATCH] Add ol.Sphere#interpolate --- src/ol/sphere/sphere.js | 36 ++++++++++++++++++++++++++++++ test/spec/ol/sphere/sphere.test.js | 20 +++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/ol/sphere/sphere.js b/src/ol/sphere/sphere.js index d63f8573c2..3f5877bc24 100644 --- a/src/ol/sphere/sphere.js +++ b/src/ol/sphere/sphere.js @@ -139,6 +139,42 @@ ol.Sphere.prototype.haversineDistance = function(c1, c2) { }; +/** + * Returns the point at `fraction` along the segment of the great circle passing + * through c1 and c2. + * + * @param {ol.Coordinate} c1 Coordinate 1. + * @param {ol.Coordinate} c2 Coordinate 2. + * @param {number} fraction Fraction. + * @return {ol.Coordinate} Coordinate between c1 and c2. + */ +ol.Sphere.prototype.interpolate = function(c1, c2, fraction) { + var lat1 = goog.math.toRadians(c1[1]); + var lon1 = goog.math.toRadians(c1[0]); + var lat2 = goog.math.toRadians(c2[1]); + var lon2 = goog.math.toRadians(c2[0]); + var cosLat1 = Math.cos(lat1); + var sinLat1 = Math.sin(lat1); + var cosLat2 = Math.cos(lat2); + var sinLat2 = Math.sin(lat2); + var cosDeltaLon = Math.cos(lon2 - lon1); + var d = sinLat1 * sinLat2 + cosLat1 * cosLat2 * cosDeltaLon; + if (1 <= d) { + return c2.slice(); + } + d = fraction * Math.acos(d); + var cosD = Math.cos(d); + var sinD = Math.sin(d); + var y = Math.sin(lon2 - lon1) * cosLat2; + var x = cosLat1 * sinLat2 - sinLat1 * cosLat2 * cosDeltaLon; + var theta = Math.atan2(y, x); + var lat = Math.asin(sinLat1 * cosD + cosLat1 * sinD * Math.cos(theta)); + var lon = lon1 + Math.atan2(Math.sin(theta) * sinD * cosLat1, + cosD - sinLat1 * Math.sin(lat)); + return [goog.math.toDegrees(lon), goog.math.toDegrees(lat)]; +}; + + /** * Returns the initial bearing from c1 to c2. * diff --git a/test/spec/ol/sphere/sphere.test.js b/test/spec/ol/sphere/sphere.test.js index 03efe01c7e..0351ea07d3 100644 --- a/test/spec/ol/sphere/sphere.test.js +++ b/test/spec/ol/sphere/sphere.test.js @@ -227,6 +227,26 @@ describe('ol.Sphere', function() { }); + describe('interpolate', function() { + + it('results match at the start, midpoint, and end', function() { + var e, i; + for (i = 0; i < expected.length; ++i) { + e = expected[i]; + var c1 = sphere.interpolate(e.c1, e.c2, 0); + expect(c1[0]).to.roughlyEqual(e.c1[0], 1e-9); + expect(c1[1]).to.roughlyEqual(e.c1[1], 1e-9); + var midpoint = sphere.interpolate(e.c1, e.c2, 0.5); + expect(midpoint[0]).to.roughlyEqual(e.midpoint[0], 1e-9); + expect(midpoint[1]).to.roughlyEqual(e.midpoint[1], 1e-9); + var c2 = sphere.interpolate(e.c1, e.c2, 1); + expect(c2[0]).to.roughlyEqual(e.c2[0], 1e-9); + expect(c2[1]).to.roughlyEqual(e.c2[1], 1e-9); + } + }); + + }); + describe('midpoint', function() { it('results match Chris Veness\'s reference implementation', function() {