/// <summary> /// Given the specified test point, this checks each segment, and will /// return the closest point on the specified segment. /// </summary> /// <param name="testPoint">The point to test.</param> /// <returns></returns> public override Coordinate ClosestPoint(Coordinate testPoint) { Coordinate closest = Coordinate; double dist = double.MaxValue; for(int i = 0; i < _points.Count - 1; i++) { LineSegment s = new LineSegment(_points[i], _points[i+1]); Coordinate temp = s.ClosestPoint(testPoint); double tempDist = testPoint.Distance(temp); if(tempDist < dist) { dist = tempDist; closest = temp; } } return closest; }
/// <summary> /// Computes the closest points on a line segment. /// </summary> /// <param name="line"></param> /// <returns> /// A pair of Coordinates which are the closest points on the line segments. /// </returns> public virtual Coordinate[] ClosestPoints(ILineSegmentBase line) { LineSegment myLine = new LineSegment(line); // test for intersection Coordinate intPt = Intersection(line); if (intPt != null) return new[] {intPt, intPt}; /* * if no intersection closest pair contains at least one endpoint. * Test each endpoint in turn. */ Coordinate[] closestPt = new Coordinate[2]; Coordinate close00 = new Coordinate(ClosestPoint(line.P0)); double minDistance = close00.Distance(line.P0); closestPt[0] = close00; closestPt[1] = new Coordinate(line.P0); Coordinate close01 = new Coordinate(ClosestPoint(line.P1)); double dist = close01.Distance(line.P1); if (dist < minDistance) { minDistance = dist; closestPt[0] = close01; closestPt[1] = new Coordinate(line.P1); } Coordinate close10 = new Coordinate(myLine.ClosestPoint(P0)); dist = close10.Distance(P0); if (dist < minDistance) { minDistance = dist; closestPt[0] = new Coordinate(P0); closestPt[1] = close10; } Coordinate close11 = new Coordinate(myLine.ClosestPoint(P1)); dist = close11.Distance(P1); if (dist < minDistance) { closestPt[0] = new Coordinate(P1); closestPt[1] = close11; } return closestPt; }
/// <summary> /// /// </summary> /// <param name="line"></param> /// <param name="pt"></param> /// <param name="locGeom"></param> private void ComputeMinDistance(ILineString line, Point pt, GeometryLocation[] locGeom) { if (line.EnvelopeInternal.Distance(pt.EnvelopeInternal) > _minDistance) return; IList<Coordinate> coord0 = line.Coordinates; Coordinate coord = pt.Coordinate; // brute force approach! for (int i = 0; i < coord0.Count - 1; i++) { double dist = CGAlgorithms.DistancePointLine(coord, coord0[i], coord0[i + 1]); if (dist < _minDistance) { _minDistance = dist; LineSegment seg = new LineSegment(coord0[i], coord0[i + 1]); Coordinate segClosestPoint = new Coordinate(seg.ClosestPoint(coord)); locGeom[0] = new GeometryLocation(line, i, segClosestPoint); locGeom[1] = new GeometryLocation(pt, 0, coord); } if (_minDistance <= _terminateDistance) return; } }