closestPoint static method
Implementation
static Point closestPoint(PickerGeometry geometry, Point point) {
// In order to find the closest line we use the point's angle
var angle = Geometry.angleFromOrigin(point);
var numVertices = geometry.vertices.length;
var relativeAngle;
var smallestRelativeAngle = Math.pi * 2;
var index1 = 0;
for (int i = 0; i < numVertices; i += 1) {
relativeAngle = Geometry.normalizeAngle(geometry.angles[i] - angle);
if (relativeAngle < smallestRelativeAngle) {
smallestRelativeAngle = relativeAngle;
index1 = i;
}
}
var index2 = (index1 - 1 + numVertices) % numVertices;
var closestLine = geometry.lines[index2];
// Provided point is within the polygon
if (Geometry.distanceFromOrigin(point) <
Geometry.lengthOfRayUntilIntersect(angle, closestLine)) {
return point;
}
Line perpendicularLine =
Geometry.perpendicularThroughPoint(closestLine, point);
Point intersectionPoint =
Geometry.intersectLineLine(closestLine, perpendicularLine);
Point bound1 = geometry.vertices[index1];
Point bound2 = geometry.vertices[index2];
Point upperBound;
Point lowerBound;
if (bound1.x > bound2.x) {
upperBound = bound1;
lowerBound = bound2;
} else {
upperBound = bound2;
lowerBound = bound1;
}
var borderPoint;
if (intersectionPoint.x > upperBound.x) {
borderPoint = upperBound;
} else if (intersectionPoint.x < lowerBound.x) {
borderPoint = lowerBound;
} else {
borderPoint = intersectionPoint;
}
return borderPoint;
}