Find the nearest point (geometry)

I want to calculate the closest point from the starting point (link) when I have the geometry point.

For this reason, I use the ports.shp file.

The code works most of the time. But sometimes it returns null minDistPoint is null. I am not sure which value is being initialized minDist.

public Point findNearestPoint( Point p, SimpleFeatureCollection features ) throws FactoryException, TransformException {
   Point destination = null;
   double minDist = 10.0e+6;
   double distance = 0;
   Point minDistPoint = null;
   try( SimpleFeatureIterator itr = features.features()) {
      while( itr.hasNext()) {
         SimpleFeature feature = itr.next();
         final String EPSG4326 =
            "GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\","+
            "SPHEROID[\"WGS 84\",6378137,298.257223563,"+
            "AUTHORITY[\"EPSG\",\"7030\"]],"+
            "AUTHORITY[\"EPSG\",\"6326\"]]," + 
            "PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],"+
            "UNIT[\"degree\", " +"0.01745329251994328,"+
            "AUTHORITY[\"EPSG\",\"9122\"]],"+
            "AUTHORITY[\"EPSG\",\"4326\"]]";
         CoordinateReferenceSystem crs = CRS.parseWKT(EPSG4326);    
         destination = (Point) feature.getDefaultGeometry(); 
         GeodeticCalculator gc = new GeodeticCalculator(crs); 
         gc.setStartingPosition(
            JTS.toDirectPosition( p.getCoordinate(), crs));
         gc.setDestinationPosition(
            JTS.toDirectPosition( dest.getCoordinate(), crs));
         distance = gc.getOrthodromicDistance();
         if( distance < minDist ) {
            minDist = distance;
            minDistPoint = destination;
            lastMatched = feature;
         }
      }
   }
   int totalmeters = (int) minDist;
   int km = totalmeters / 1000;
   int meters = totalmeters - (km * 1000);
   float remaining_cm = (float) (minDist - totalmeters) * 10000;
   remaining_cm = Math.round(remaining_cm);
   float cm = remaining_cm / 100;
   System.out.println(
      "Distance = " + km + "km " + meters + "m " + cm + "cm");
   if( minDistPoint == null ) {
      return null;
   }
   return minDistPoint;
}
+4
source share
2 answers

With each algorithm, to find the minimum, you should always set the initial value either for the first of the set or for the maximum possible value.

, double, Double.POSITIVE_INFINITY , , if .

+1

, Double.PositiveInfinity . , pi * r. goood 3,14 * 6400 . .

0

Source: https://habr.com/ru/post/1682199/


All Articles