I want to compute the nearest point from a starting point (reference) when I have geometry point
.
I am using the ports.shp file for this reason.
The code works most of the time.But sometimes it returns null minDistPoint is null
. I am not sure with what value to initialize 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;
}
With every algorithm to find the minimum, you should always set the initial value to either the first one of the set or the maximum value achievable.
In your case, since you are using a double, you can use Double.POSITIVE_INFINITY
as initial value, this will allow you to assure that at least the first time the if
condition will be true.