当我具有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;
}
最佳答案
在使用每种算法寻找最小值时,应始终将初始值设置为集合中的第一个或可达到的最大值。
在您的情况下,由于使用的是双精度型,因此可以将Double.POSITIVE_INFINITY
用作初始值,这将使您至少可以确保if
条件第一次为真。