Android Location.distanceTo(...) and Location.bearingTo(...) not returning correct results

Adam Davies picture Adam Davies · Apr 19, 2013 · Viewed 8.1k times · Source

I've been though dozens of posts on this so please do not flag this as a duplicate because it isn't.

So running the following code:

private void testLocation(){
    double currentLat = 51.43376;
    double currentLng = -2.86221;

    double destLat = 51.43503; 
    double destLng = -2.86869;

    final float[] results= new float[3];
    Location.distanceBetween(currentLat, currentLng, destLat, destLng, results);
    Log.d("GPS", "results[0]: " + results[0]);
    Log.d("GPS", "results[1]: " + results[1]);
    Log.d("GPS", "results[2]: " + results[2]);


    Location here = new Location("Current");
    here.setLatitude(currentLat);
    here.setLatitude(currentLng);

    Location dest = new Location("Destination2");
    dest.setLatitude(destLat);
    dest.setLongitude(destLng);


    Log.d("GPS", "Bearing to dest: " + here.bearingTo(dest));
    Log.d("GPS", "Distance to dest: " + here.distanceTo(dest));
}

The output is:

04-19 13:39:55.850: D/GPS(12398): results[0]: 472.2533
04-19 13:39:55.860: D/GPS(12398): results[1]: -72.5882
04-19 13:39:55.860: D/GPS(12398): results[2]: -72.59327
04-19 13:39:55.860: D/GPS(12398): Bearing to dest: 120.83207
04-19 13:39:55.860: D/GPS(12398): Distance to dest: 7893878.5

The correct values should be: Distance 472.2533 (So results[0] is correct). Bearing 285.454 degrees

So I don't know what results[1] and results[2] are giving. And both bearingTo and distanceTo are giving completely the wrong answers.

This means that I must be doing something wrong. Can anyone help. Generally, all I want to do is calculate the distance and direction of a destination point from a current location point. If anyone has a better way for doing that than that shown above, or knows what I am doing wrong please help.

Thanks Adam

Answer

Samuel picture Samuel · Apr 19, 2013

The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2] - docs

You're setting the latitude twice with two different values here:

here.setLatitude(currentLat);
here.setLatitude(currentLng);

And you mixed up the lat/long values here:

dest.setLongitude(destLat);
dest.setLatitude(destLng);

Check and see if that fixes your problems

The two methods of computing distance and bearing should produce identical results because the same method is used to compute those results. Look at the source code of the SDK.