Android: distanceTo() wrong values

只愿长相守 提交于 2019-12-13 03:05:54

问题


I am writing an application for tracking my route. I am requesting updates from GPS every minute and it works fine. It shows me my exact point. When I want to calculate distance between current point and previous one it works ok, but form time to time it calculates distance totaly wrong (I moved about 200m and it retuned me a value over 10km). Does anyone know why this could happen?

Here is the function which I use:

iRoute += myGPSLocation.distanceTo(prevLocation);

Thanks in advance!


回答1:


Stop using google's Location.distancebetween & location.distanceto functions. They don't work consistently.

Instead use the direct formula to calculate the distance:

double distance_between(Location l1, Location l2)
{
    //float results[] = new float[1];
    /* Doesn't work. returns inconsistent results
    Location.distanceBetween(
            l1.getLatitude(),
            l1.getLongitude(),
            l2.getLatitude(),
            l2.getLongitude(),
            results);
            */
    double lat1=l1.getLatitude();
    double lon1=l1.getLongitude();
    double lat2=l2.getLatitude();
    double lon2=l2.getLongitude();
    double R = 6371; // km
    double dLat = (lat2-lat1)*Math.PI/180;
    double dLon = (lon2-lon1)*Math.PI/180;
    lat1 = lat1*Math.PI/180;
    lat2 = lat2*Math.PI/180;

    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double d = R * c * 1000;

    log_write("dist betn "+
            d + " " +
            l1.getLatitude()+ " " +
            l1.getLongitude() + " " +
            l2.getLatitude() + " " +
            l2.getLongitude()
            );

    return d;
}



回答2:


distanceTo() works correctly.
The error is on your side, most probable algorithmic one, e.g if there is no GPS fix available, and the phone takes a GSM cell based location, this of course can be off by 1000m.

For your app that probably wants to sum up the distance travelled, take only GPS fixes, don't use another LocationProvider than GPS!



来源:https://stackoverflow.com/questions/18377587/android-distanceto-wrong-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!