Class PointPairDistance

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12  
13 package org.locationtech.jts.algorithm.distance;
14  
15 import org.locationtech.jts.geom.Coordinate;
16 import org.locationtech.jts.io.WKTWriter;
17  
18 /**
19  * Contains a pair of points and the distance between them.
20  * Provides methods to update with a new point pair with
21  * either maximum or minimum distance.
22  */
23 public class PointPairDistance {
24  
25   private Coordinate[] pt = { new Coordinate(), new Coordinate() };
26   private double distance = Double.NaN;
27   private boolean isNull = true;
28  
29   public PointPairDistance()
30   {
31   }
32  
33   public void initialize() { isNull = true; }
34  
35   public void initialize(Coordinate p0, Coordinate p1)
36   {
37     pt[0].setCoordinate(p0);
38     pt[1].setCoordinate(p1);
39     distance = p0.distance(p1);
40     isNull = false;
41   }
42  
43   /**
44    * Initializes the points, avoiding recomputing the distance.
45    * @param p0
46    * @param p1
47    * @param distance the distance between p0 and p1
48    */
49   private void initialize(Coordinate p0, Coordinate p1, double distance)
50   {
51     pt[0].setCoordinate(p0);
52     pt[1].setCoordinate(p1);
53     this.distance = distance;
54     isNull = false;
55   }
56  
57   public double getDistance() { return distance; }
58  
59   public Coordinate[] getCoordinates() { return pt; }
60  
61   public Coordinate getCoordinate(int i) { return pt[i]; }
62  
63   public void setMaximum(PointPairDistance ptDist)
64   {
65     setMaximum(ptDist.pt[0], ptDist.pt[1]);
66   }
67  
68   public void setMaximum(Coordinate p0, Coordinate p1)
69   {
70     if (isNull) {
71       initialize(p0, p1);
72       return;
73     }
74     double dist = p0.distance(p1);
75     if (dist > distance)
76       initialize(p0, p1, dist);
77   }
78  
79   public void setMinimum(PointPairDistance ptDist)
80   {
81     setMinimum(ptDist.pt[0], ptDist.pt[1]);
82   }
83  
84   public void setMinimum(Coordinate p0, Coordinate p1)
85   {
86     if (isNull) {
87       initialize(p0, p1);
88       return;
89     }
90     double dist = p0.distance(p1);
91     if (dist < distance)
92       initialize(p0, p1, dist);
93   }
94   
95   public String toString()
96   {
97       return WKTWriter.toLineString(pt[0], pt[1]);
98   }
99 }
100