01: package com.vividsolutions.jump.algorithm;
02:
03: import com.vividsolutions.jts.geom.*;
04:
05: /**
06: * Computes the length along a LineString to the point on the line nearest a given point.
07: */
08: //Martin made a decision to create this duplicate of a class from JCS.
09: //[Jon Aquino 2004-10-25]
10: public class LengthToPoint {
11: public static double lengthAlongSegment(LineSegment seg,
12: Coordinate pt) {
13: double projFactor = seg.projectionFactor(pt);
14: double len = 0.0;
15: if (projFactor <= 0.0)
16: len = 0.0;
17: else if (projFactor <= 1.0)
18: len = projFactor * seg.getLength();
19: else
20: len = seg.getLength();
21: return len;
22: }
23:
24: /**
25: * Computes the length along a LineString to the point on the line nearest a given point.
26: */
27: public static double length(LineString line, Coordinate inputPt) {
28: LengthToPoint lp = new LengthToPoint(line, inputPt);
29: return lp.getLength();
30: }
31:
32: private double minDistanceToPoint;
33: private double locationLength;
34:
35: public LengthToPoint(LineString line, Coordinate inputPt) {
36: computeLength(line, inputPt);
37: }
38:
39: public double getLength() {
40: return locationLength;
41: }
42:
43: private void computeLength(LineString line, Coordinate inputPt) {
44: minDistanceToPoint = Double.MAX_VALUE;
45: double baseLocationDistance = 0.0;
46: Coordinate[] pts = line.getCoordinates();
47: LineSegment seg = new LineSegment();
48: for (int i = 0; i < pts.length - 1; i++) {
49: seg.p0 = pts[i];
50: seg.p1 = pts[i + 1];
51: updateLength(seg, inputPt, baseLocationDistance);
52: baseLocationDistance += seg.getLength();
53:
54: }
55: }
56:
57: private void updateLength(LineSegment seg, Coordinate inputPt,
58: double segStartLocationDistance) {
59: double dist = seg.distance(inputPt);
60: if (dist > minDistanceToPoint)
61: return;
62: minDistanceToPoint = dist;
63: // found new minimum, so compute location distance of point
64: double projFactor = seg.projectionFactor(inputPt);
65: if (projFactor <= 0.0)
66: locationLength = segStartLocationDistance;
67: else if (projFactor <= 1.0)
68: locationLength = segStartLocationDistance + projFactor
69: * seg.getLength();
70: else
71: locationLength = segStartLocationDistance + seg.getLength();
72: }
73: }
|