我想從幾何起點(參考)計算最近點,當我有幾何圖形point
。找到最近點(幾何點)
由於這個原因,我正在使用ports.shp文件。
該代碼大部分時間都有效,但有時會返回空值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'條件爲真。 – bracco23
@ bracco23:它似乎工作正常,謝謝!讓它成爲一個答案,請。 – George