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