Distance calculation
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
class DistanceUtil {
private LocationManager _lm;
private String _provider;
public DistanceUtil(Context context) {
_lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_COARSE);
if (_lm != null)
_provider = _lm.getBestProvider(crit, true);
}
public static double calculateDistance(double startLat, double startLong,
double endLat, double endLong) {
try {
double theta = startLong - endLong;
double dist = Math.sin(deg2rad(startLat))
* Math.sin(deg2rad(endLat)) + Math.cos(deg2rad(startLat))
* Math.cos(deg2rad(endLat)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515; // in miles
dist = dist * 1.609344; // in kilometers
return dist;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public double calculateDistanceFromActual(double endLat, double endLong) {
if (_lm != null && _provider != null) {
Location loc = _lm.getLastKnownLocation(_provider);
if (loc != null)
return calculateDistance(loc.getLatitude(), loc.getLongitude(),
endLat, endLong);
}
return 0;
}
private static double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private static double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
Related examples in the same category