1

In my Android application I am trying to calculate the distance between two locations but the values I am getting is in tens of Millions 11Million+. The actual distance between the two point/location is just 1.1km - 1.3Km. Why is this so? Even if the value the .distanceTo method returns is in meters 11M meters is still a very big value.

Here is my code:

        Location locationA = new Location("LocationA");
        locationA.setLatitude(lat);
        locationA.setLongitude(lang);

        Location locationB = new Location("LocationB");
        locationB.setLatitude(14.575224);
        locationB.setLongitude(121.042475);

        float distance = locationA.distanceTo(locationB);
        BigDecimal _bdDistance;
        _bdDistance = round(distance,2);
        String _strDistance = _bdDistance.toString();      

Toast.makeText(this, "distance between two locations = "+_strDistance, Toast.LENGTH_SHORT).show();

  public static BigDecimal round(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd;
    }
TwoThumbSticks
  • 1,086
  • 3
  • 23
  • 38
  • 1
    the way you round looks concerning. [`Math.round(float)`](http://developer.android.com/reference/java/lang/Math.html#round%28float%29) should work just fine and if you really want 2 decimal precision do it without string conversion like in http://stackoverflow.com/a/3596122 – zapl Nov 19 '15 at 09:10

2 Answers2

8

Your approximation is right. It returns the distance in meters.

You can convert it to KM by dividing it by 1000 like so;

float distance = locationA.distanceTo(locationB)/1000;

Read more about distanceTo here.

vguzzi
  • 2,420
  • 2
  • 15
  • 19
  • 1
    Like what I wrote in my question sir it is returning 11Million (11,000,000) meters when it is only 1.1 kilometers away. Even if I divide it by (1,000) the value still seems very large (11,000km). – TwoThumbSticks Nov 19 '15 at 10:01
  • Give me the latitude and longitude which your passing in for locationA. – vguzzi Nov 19 '15 at 10:06
  • 3
    Oh my thank you for asking for the locationA parameters. The location A parameter is supplied by a method and in the method I found that I was actually passing the latitude value instead of my longitude value on the parameter for longitude. – TwoThumbSticks Nov 19 '15 at 10:18
  • Haha, no worries, glad you found it. :) – vguzzi Nov 19 '15 at 10:20
-2

here in my screenshot you can see, if we take location from double latitude, longitude i.e. 6 digit after decimal but actually Location hold latitude value till 8 digits. The main difference is here. So don't use double for storing latitude, longitude. Try to use anotherway

  • 1
    You forgot your screenshot. However, a double has plenty of precision for positions accurate to within millimeters; single precision float is sufficient for precision near one meter. – Martijn Pieters Apr 04 '20 at 20:10