我正在使用开放的街道地图。现在我可以获得地图中的所有交叉点,并可以获得它们的经度和纬度..我的应用程序中也有GPS 我想要做的是找到我的GPS坐标最近的交叉点 这是我的方法,但不是很准确。我只是需要帮助才能知道原因!感谢..
public Nodee nearestPoint(double longitude, double latitude) throws Exception {
inters = new ArrayList<Nodee>();
inters = getIntersections();
double minLong = Math.abs(longitude - (inters.get(0).lon));
double minLat = Math.abs(latitude - (inters.get(0).lat));
Nodee NearestNodeLong = null;
Nodee NearestNodeLat = null;
for (int i = 0; i < inters.size(); i++) {
if (Math.abs((inters.get(i).lon) - longitude) < minLong) {
minLong = (Math.abs((inters.get(i).lon) - longitude));
NearestNodeLong = inters.get(i);
}
if (Math.abs((inters.get(i).lat) - latitude) < minLat) {
minLat = Math.abs((inters.get(i).lat) - latitude);
NearestNodeLat = inters.get(i);
}
}
if (NearestNodeLong.equals(NearestNodeLat)) {
return NearestNodeLong;
} else if (!NearestNodeLong.equals(NearestNodeLat)) {
Double d1 = (double) distFrom(latitude, longitude, (NearestNodeLat.lat),
(NearestNodeLat.lon));
Double d2 = (double) distFrom(latitude, longitude, (NearestNodeLong.lat),
(NearestNodeLong.lon));
if (d1 < d2)
return NearestNodeLat;
else if (d2 < d1)
return NearestNodeLong;
}
return null;
}
答案 0 :(得分:0)
试试这个解决方案:
public Nodee nearestPoint(double longitude, double latitude) throws Exception {
Nodee result = null;
double maxDifference = 0.1;
ArrayList<Nodees> filteredNodes = getBox(longitude, latitude, maxDifference);
if ( filteredNodes.size()<=0) return null;
double minDistance = calcDistance(longitude, latitude,
filteredNodes.get(0).lon,filteredNodes.get(0).lon);
result = filteredNodes.get(0);
for (int i=1; i<filteredNodes.size();i++){
Nodee current = filteredNodes.get(i);
double diffDistance = calcDistance(longitude, latitude,
filteredNodes.get(i).lon,filteredNodes.get(i).lon);
if( minDistance > diffDistance){
minDistance = diffDistance;
result = current;
}
}
return result;
}
public ArrayList<Nodee> getBox(double lon, double lat, double diff) throws Exception{
ArrayList<Nodee> inters = getIntersections();
ArrayList<Nodee> result = new ArrayList<Nodee>();
for (int i=0; i<inters.size(); i++){
if(Math.abs(inters.get(i).lat-lat)<=diff &&
Math.abs(inters.get(i).lon-lon)<=diff)
result.add(inters.get(i));
}
return result();
}
public double calcDistance(lon1, lat1, lon2, lat2){
deltaLon = lon1-lon2;
deltaLat = lat1-lat2;
return Math.sqrt(deltaLon*deltaLon+deltaLat*deltaLat);
}