raghumudem - 1 year ago 129

Android Question

Here my code I used below code to calculate the distance between two location using their latitude and longitude. It is giving wrong distance. sometimes getting right and sometimes getting irrelevant distance.

We are getting lat1 and lng1 from database.

`//getting lat2 and lng2 from GPS as below`

public class MyLocationListener implements LocationListener {

@Override

public void onLocationChanged(Location loc)

{

lat2=loc.getLatitude();

lng2=loc.getLongitude();

String Text = "My current location is: " +"Latitud = "+ loc.getLatitude() +"Longitud = " + loc.getLongitude();

//System.out.println("Lat & Lang form Loc"+Text);

//Toast.makeText( getApplicationContext(), Text,Toast.LENGTH_SHORT).show();

}

@Override

public void onProviderDisabled(String provider)

{

}

@Override

public void onProviderEnabled(String provider)

{

}

@Override

public void onStatusChanged(String provider, int status, Bundle extras)

{

}

//Calculating distance

double earthRadius = 3958.75;

double dLat = Math.toRadians(lat1-lat2);

double dLng = Math.toRadians(lng1-lng2);

double a = Math.sin(dLat/2) * Math.sin(dLat/2) +

Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(lat1)) *

Math.sin(dLng/2) * Math.sin(dLng/2);

double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

double dist = earthRadius * c;

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
private double distance(double lat1, double lon1, double lat2, double lon2) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**