找到最近点(几何点)

时间:2017-07-25 09:22:40

标签: java gis geotools

当我有几何point时,我想计算起点(参考)的最近点。

我正在使用ports.shp文件。

代码大部分时间都有效。但有时它会返回null minDistPoint is null。我不确定初始化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;
}

2 个答案:

答案 0 :(得分:1)

每个算法都要找到最小值,你应该始终将初始值设置为集合中的第一个或可达到的最大值。

在您的情况下,由于您使用的是double,因此您可以使用Double.POSITIVE_INFINITY作为初始值,这样您就可以确保至少第一次if条件为真。< / p>

答案 1 :(得分:0)

计算机科学答案在评论中给出,Double.PositiveInfinity比任何数字都大。 地理空间的答案是在球体上没有两个点比pi * r更远。对于行星地球,上限为3.14 * 6400 km。 使用正无穷大。