2

Following two line calculate the lat and lng

double geoLat = location.getLatitude(); //  37.422006
double geoLng = location.getLongitude(); //   -122.084095

In a loop i calculate the distance array between geo points. latitude[i] and longitude[i] comes as json response from google map api

distance[i]=GetLatAndLng.gps2m(geoLat, geoLng,latitude[i] ,longitude[i]);

This is gps2m method.

public static double gps2m(double lat1, double lng1, double lat2, double lng2) {
 double l1 = Math.toRadians(lat1);
    double l2 = Math.toRadians(lat2);
    double g1 = Math.toRadians(lng1);
    double g2 = Math.toRadians(lng2);

    double dist = Math.acos(Math.sin(l1) * Math.sin(l2) + Math.cos(l1) * Math.cos(l2) * Math.cos(g1 - g2));
    if(dist < 0) {
        dist = dist + Math.PI;
    }
    return Math.round(dist * 6378100);//in meters

}
}

In the distance array i m getting value like 1.1967617E7 I want distance in meters

What is going wrong and how to get distance in meters.

Help!!

Sunny
  • 14,522
  • 15
  • 84
  • 129

2 Answers2

5

You can use the Location class. You can calculate the distance in two ways:

location.distanceTo(anotherLocation);

or

Location.distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results);

Take a look at the Location documentation for more details.

Franziskus Karsunke
  • 4,948
  • 3
  • 40
  • 54
4

Here is my code:

int EARTH_RADIUS_KM = 6371;
double lat1,lon1,lat2,lon2,lat1Rad,lat2Rad,deltaLonRad,dist,nDist;
lat1 = latitude of location 1

lon1 = longitude of location 1

lat2 = latitude of location 2

lon2 = longitude of location 2

lat1Rad = Math.toRadians(lat1);

lat2Rad = Math.toRadians(lat2);

deltaLonRad = Math.toRadians(lon2 - lon1);

dist = Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM;

nDist = Math.round(dist*0.62);

String strDistance = Double.toString(nDist)+" Miles";

The dist you get is in double and KM, you might want to round up the value that you're getting, do this by using Math.round(dist*0.62);

*0.62 is to convert KM into miles.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
ZealDeveloper
  • 783
  • 5
  • 21