使用gps纬度经度获得不正确的距离

时间:2014-05-06 09:35:25

标签: java android

这是我的代码:

private final static double[] multipliers = {
        1.0, 1.0936133, 0.001, 0.000621371192
};

private final static String[] unitstrings = {
        "m", "y", "km", "mi"
};

private void updateMeasurement() {
    double distance = calcGeoDistance(startLat, startLon, currentLat, currentLon) * multipliers[unitindex];
    String distanceText = "" + RoundDecimal(distance, 2) + " " + unitstrings[unitindex];    
    ((TextView)findViewById(R.id.distance)).setText(distanceText);
}

private double calcGeoDistance(final double lat1, final double lon1, final double lat2, final double lon2)
{
    double distance = 0.0;       
    try
    {
        final float[] results = new float[3];           
        Location.distanceBetween(lat1, lon1, lat2, lon2, results);         
        distance = (double)results[0];
    }
    catch (final Exception ex)
    {
        distance = 0.0;
    }
    return distance;
}

即使摇动手机,我也能获得8310公里。

2 个答案:

答案 0 :(得分:0)

public float distanceFrom(float lat1, float lng1, float lat2, float lng2) {

    double earthRadius = 3958.75;
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = 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(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = earthRadius * c;
    int meterConversion = 1609;
    return new Float(dist * meterConversion).floatValue();
}

答案 1 :(得分:0)

您是否使用正确格式的Long和Lat?这将有助于查看您传递的值

double startLatitude = pointStart.getLatitudeE6() / DEG_RATE;
double startLongitude= pointStart.getLongitudeE6() / DEG_RATE;
double endLatitude = pointEnd.getLatitudeE6() / DEG_RATE;
double endLongitude= pointEnd.getLongitudeE6() / DEG_RATE;
float[] result = new float[1];
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, result);

其中pointStart和pointEnd是com.google.android.maps.GeoPoint

参考 -

http://www.java2s.com/Code/Android/Core-Class/GetDistancebetweentwoGeoPoint.htm