0

我正在使用开放的街道地图。现在我可以获取地图中的所有交点,并可以获取它们的经度和纬度。我的应用程序中有 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;

}
4

1 回答 1

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);
}
于 2012-05-15T06:42:18.343 回答