Merge pull request #917 from Turbo87/segment-distance

Geometry: Added distanceSquaredToSegment() function
This commit is contained in:
ahocevar
2013-03-25 12:30:05 -07:00
2 changed files with 38 additions and 11 deletions

View File

@@ -438,12 +438,39 @@ OpenLayers.Geometry.segmentsIntersect = function(seg1, seg2, options) {
* representing endpoint coordinates.
*
* Returns:
* {Object} An object with distance, x, and y properties. The distance
* {Object} An object with distance, along, x, and y properties. The distance
* will be the shortest distance between the input point and segment.
* The x and y properties represent the coordinates along the segment
* where the shortest distance meets the segment.
* where the shortest distance meets the segment. The along attribute
* describes how far between the two segment points the given point is.
*/
OpenLayers.Geometry.distanceToSegment = function(point, segment) {
var result = OpenLayers.Geometry.distanceSquaredToSegment(point, segment);
result.distance = Math.sqrt(result.distance);
return result;
};
/**
* Function: OpenLayers.Geometry.distanceSquaredToSegment
*
* Usually the distanceToSegment function should be used. This variant however
* can be used for comparisons where the exact distance is not important.
*
* Parameters:
* point - {Object} An object with x and y properties representing the
* point coordinates.
* segment - {Object} An object with x1, y1, x2, and y2 properties
* representing endpoint coordinates.
*
* Returns:
* {Object} An object with squared distance, along, x, and y properties.
* The distance will be the shortest distance between the input point and
* segment. The x and y properties represent the coordinates along the
* segment where the shortest distance meets the segment. The along
* attribute describes how far between the two segment points the given
* point is.
*/
OpenLayers.Geometry.distanceSquaredToSegment = function(point, segment) {
var x0 = point.x;
var y0 = point.y;
var x1 = segment.x1;
@@ -466,7 +493,8 @@ OpenLayers.Geometry.distanceToSegment = function(point, segment) {
y = y1 + along * dy;
}
return {
distance: Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)),
x: x, y: y
distance: Math.pow(x - x0, 2) + Math.pow(y - y0, 2),
x: x, y: y,
along: along
};
};