GPS距离计算

时间:2011-12-13 18:30:59

标签: gps haversine

我想计算两个GPS位置之间的距离,每个位置都有一个latitute值和一个经度值。对于短距离结果,计算应该是准确的。例如。 < 3亿英镑。如果我使用Google Earth(请参阅我的代码中的coord),距离约为136米。 如果我使用文章提供的解决方案:http://www.movable-type.co.uk/scripts/latlong.html(hasrsine公式),那么结果就没那么了。

使用过的代码:

public void GpsCalc(){
    double d = getDistance(51.342299,4.371359, 51.342490,4.371997); 
    Log.e("GpsCalc", String.valueOf(d));
}

public static double getDistance(double lat1, double lng1, double lat2, double lng2){
    double R = 6371; // earth’s radius (mean radius = 6,371km)
    double dLat =  Math.toRadians(lat2-lat1);

    double dLon =  Math.toRadians(lng2-lng1); 
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
               Math.sin(dLon/2) * Math.sin(dLon/2); 
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    double dr1 = R * c;//in radians      

    Log.e("getDistance-dr1", String.valueOf(dr1));

    return dr1;
}

我确信这应该是一些小改动,但我看不到它。

2 个答案:

答案 0 :(得分:1)

我也遇到了该页面上的半胱氨酸配方问题。我知道这不是你的问题的答案,但我在余弦公式中获得了更多的成功,它给出了与Google Earth相同的结果。如果它有帮助,它看起来像这样:

public double getDistance(double lat1, double lon1, double lat2, double lon2) {
    double latA = Math.toRadians(lat1);
    double lonA = Math.toRadians(lon1);
    double latB = Math.toRadians(lat2);
    double lonB = Math.toRadians(lon2);
    double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
                    (Math.sin(latA) * Math.sin(latB));
    double ang = Math.acos(cosAng);
    double dist = ang * EARTH_RADIUS;
    return dist;
}

修改

我在谷歌地图和谷歌地球以及我的代码中尝试了你的坐标,我所有人都得到49米。也许从来没有问题? screenshot

答案 1 :(得分:1)

有点晚了,但还有两个选择

  1. 使用Apple Corelocation(49.2733米)

    CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:_posGPSCurrent.latitude longitude:_posGPSCurrent.longitude];
    
    CLLocation *location = [[CLLocation alloc] initWithLatitude:_posGPSTarget.latitude longitude:_posGPSTarget.longitude];
    
    // in kilometers
    CLLocationDistance distance =[currentLocation distanceFromLocation:location]/1000;
    
  2. 手动计算(49.1393米)

  3. 包含数学库

    #include <math.h>
    
    // distance in Kilometers (Haversine)
    
    -(double)distanceFromGPSlat1:(double)tlat1 lon2:(double)tlon1 lat2:(double)tlat2 lon2:(double)tlon2
    {
    double distance = ((acos(sin(tlat1*M_PI/180)*sin(tlat2*M_PI/180)+cos(tlat1*M_PI/180)*cos(tlat2*M_PI/180)*cos((tlon1-tlon2)*M_PI/180))*180/M_PI)*60*1.1515*1.609344);
    
    return distance;
    }
    

    也许我更喜欢第二种方法(手动计算)。