0

i use the following distance formula for find out distance b/w two locations in andorid but not give the accurate distance

public double calculatedistancenew(String s1, String s2) {

 int Radius=6371;//radius of earth in Km         
 double dLat = Math.toRadians(lati-Double.valueOf(s1));
 double dLon = Math.toRadians(longg-Double.valueOf(s2));
 double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
 Math.cos(Math.toRadians(lati)) * Math.cos(Math.toRadians(Double.valueOf(s1))) * Math.sin(dLon/2) * Math.sin(dLon/2);
 double c = 2 * Math.asin(Math.sqrt(a));
 double valueResult= Radius*c;
 double km=valueResult/1;
 DecimalFormat newFormat = new DecimalFormat("####");
 float kmInDec =  Float.valueOf(newFormat.format(km));
 double meter=valueResult%1000;
 int  meterInDec= Integer.valueOf(newFormat.format(meter));
 Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);
 double kmindis=Math.floor(valueResult*100)/100;
 return kmindis;

}

Angel
  • 11
  • 4

2 Answers2

0

Use the following code to calculate distance between two locations

Location location1 = new Location("A");
Location location2 = new Location("B");

location1.setLatitude(dLat1);
location1.setLongitude(dLon1);

location2.setLatitude(dLat2);
location2.setLongitude(dLon2);

float distance = location1.distanceTo(location2);`

the calculated value is in meters.

Praveen Kumar
  • 547
  • 1
  • 7
  • 33
0

it is rather easy to do, you can check googlemaps utils library, method "computeDistanceBetween":

https://github.com/googlemaps/android-maps-utils/blob/9085396a1cb5703db568241937ffa330ff099d4e/library/src/com/google/maps/android/SphericalUtil.java

static double havDistance(double lat1, double lat2, double dLng) {
    return hav(lat1 - lat2) + hav(dLng) * cos(lat1) * cos(lat2);
}

static double arcHav(double x) {
    return 2 * asin(sqrt(x));
}

private static double distanceRadians(double lat1, double lng1, double lat2, double lng2) {
    return arcHav(havDistance(lat1, lat2, lng1 - lng2));
}

static double computeAngleBetween(LatLng from, LatLng to) {
    return distanceRadians(toRadians(from.latitude), toRadians(from.longitude),
                           toRadians(to.latitude), toRadians(to.longitude));
}

public static double computeDistanceBetween(LatLng from, LatLng to) {
    return computeAngleBetween(from, to) * EARTH_RADIUS;
}

Some methods could have missing refences here, check the github code for full code!

N Dorigatti
  • 3,482
  • 2
  • 22
  • 33