From 5d36c2a55e4e168fc18d1441bd18f22ec28b2b72 Mon Sep 17 00:00:00 2001 From: Tom Payne Date: Sat, 7 Dec 2013 12:42:21 +0100 Subject: [PATCH] Add ol.geom.flat.closestPoint --- src/ol/geom/flatgeom.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/ol/geom/flatgeom.js b/src/ol/geom/flatgeom.js index 8e87578e94..588858d624 100644 --- a/src/ol/geom/flatgeom.js +++ b/src/ol/geom/flatgeom.js @@ -5,6 +5,39 @@ goog.require('goog.asserts'); goog.require('goog.vec.Mat4'); +/** + * Returns the point on the line segment (x1, y1) to (x2, y2) that is closest to + * the point (x, y). + * @param {number} x X. + * @param {number} y Y. + * @param {number} x1 X1. + * @param {number} y1 Y1. + * @param {number} x2 X2. + * @param {number} y2 Y2. + * @param {Array.} closestPoint Closest point. + */ +ol.geom.flat.closestPoint = function(x, y, x1, y1, x2, y2, closestPoint) { + var dx = x2 - x1; + var dy = y2 - y1; + if (dx === 0 && dy === 0) { + closestPoint[0] = x1; + closestPoint[1] = y1; + } else { + var t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); + if (t > 1) { + closestPoint[0] = x2; + closestPoint[1] = y2; + } else if (t > 0) { + closestPoint[0] = x1 + dx * t; + closestPoint[1] = y1 + dy * t; + } else { + closestPoint[0] = x1; + closestPoint[1] = y1; + } + } +}; + + /** * @param {Array.} flatCoordinates Flat coordinates. * @param {number} offset Offset.