Class DistanceToPointFinder

 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 package org.locationtech.jts.operation.buffer.validate;
13  
14 import org.locationtech.jts.geom.Coordinate;
15 import org.locationtech.jts.geom.Geometry;
16 import org.locationtech.jts.geom.GeometryCollection;
17 import org.locationtech.jts.geom.LineSegment;
18 import org.locationtech.jts.geom.LineString;
19 import org.locationtech.jts.geom.Polygon;
20  
21 /**
22  * Computes the Euclidean distance (L2 metric) from a Point to a Geometry.
23  * Also computes two points which are separated by the distance.
24  */
25 public class DistanceToPointFinder {
26  
27   public DistanceToPointFinder() {
28   }
29  
30   public static void computeDistance(Geometry geom, Coordinate pt, PointPairDistance ptDist)
31   {
32     if (geom instanceof LineString) {
33       computeDistance((LineString) geom, pt, ptDist);
34     }
35     else if (geom instanceof Polygon) {
36       computeDistance((Polygon) geom, pt, ptDist);
37     }
38     else if (geom instanceof GeometryCollection) {
39       GeometryCollection gc = (GeometryCollection) geom;
40       for (int i = 0; i < gc.getNumGeometries(); i++) {
41         Geometry g = gc.getGeometryN(i);
42         computeDistance(g, pt, ptDist);
43       }
44     }
45     else { // assume geom is Point
46       ptDist.setMinimum(geom.getCoordinate(), pt);
47     }
48   }
49   public static void computeDistance(LineString line, Coordinate pt, PointPairDistance ptDist)
50   {
51     Coordinate[] coords = line.getCoordinates();
52     LineSegment tempSegment = new LineSegment();
53     for (int i = 0; i < coords.length - 1; i++) {
54       tempSegment.setCoordinates(coords[i], coords[i + 1]);
55       // this is somewhat inefficient - could do better
56       Coordinate closestPt = tempSegment.closestPoint(pt);
57       ptDist.setMinimum(closestPt, pt);
58     }
59   }
60  
61   public static void computeDistance(LineSegment segment, Coordinate pt, PointPairDistance ptDist)
62   {
63     Coordinate closestPt = segment.closestPoint(pt);
64     ptDist.setMinimum(closestPt, pt);
65   }
66  
67   public static void computeDistance(Polygon poly, Coordinate pt, PointPairDistance ptDist)
68   {
69     computeDistance(poly.getExteriorRing(), pt, ptDist);
70     for (int i = 0; i < poly.getNumInteriorRing(); i++) {
71       computeDistance(poly.getInteriorRingN(i), pt, ptDist);
72     }
73   }
74 }
75