Calculate Distance traveled android using location manager [duplicate] - android

This question already has answers here:
Android Calculate Distance Traveled
(2 answers)
Closed 6 years ago.
I am currently working on a simple fitness app that allows user to track his/her performance (running,walking). I have been using location manager to get the moving speed which works very fine. However I need to get the distance traveled, how can use location manager (long and lat) to get the distance ?
Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track);
start = (Button) findViewById(R.id.btnStart);
speed = (TextView) findViewById(R.id.txtSpeed);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//initialize location listener
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
getSpeed(location);
double lat2 = location.getLatitude();
double lng2 = location.getLongitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
//get the speed from the given location updates
public void getSpeed(Location location) {
currentSpeed = (location.getSpeed() * 3600 / 1000);
String convertedSpeed = String.format("%.2f", currentSpeed);
speed.setText(convertedSpeed + "Km/h");
}
};

You can possibly find distance between each successive latitude and longitude and keep adding.
Here getting distance in kilometers (km)
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);
}
Hope this helps you.

Related

Why cannot get the distance using both location which fetch from firebase realtime database

I am new in Java and Firebase. Now I have try to using the geolocation of two location that get from database and calculate the distance in km using the geolocation formula.
The coding as shown below.
private void getUserLocation() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("UserID")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("User location");
ValueEventListener listener = databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userlatitude = dataSnapshot.child("latitude").getValue(String.class);
userlongitude = dataSnapshot.child("longitude").getValue(String.class);
Double UserLatitude = Double.parseDouble(userlatitude);
Double UserLongitude = Double.parseDouble(userlongitude);
//String Userlatitudedouble = String.valueOf(UserLatitude);
//String Userlongitudedouble = String.valueOf(UserLongitude);
Log.i("user double latitude", userlatitude);
Log.i("User double longitude", userlongitude);
Double hostlatitudedouble = Double.parseDouble(latitude_host);
Double hostlongitudedouble = Double.parseDouble(longitude_host);
//String hostlatitudedouble = String.valueOf(HostLatitude);
//String hostlongitudedouble = String.valueOf(HostLongitude);
Log.i("host double latitude", latitude_host);
Log.i("host double longitude", longitude_host);
getDistance(UserLatitude, UserLongitude, hostlatitudedouble, hostlongitudedouble);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private double rad2deg(double distance) {
return (distance * 180.0/Math.PI);
}
private double deg2rad(double lat1) {
return (lat1 * Math.PI / 180.0);
}
private void getDistance(double lat1, double long1, double lat2, double long2) {
double longdiff = long1 - long2;
double distance = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
+ Math.cos(deg2rad(longdiff));
distance = Math.acos(distance);
String testing= String.valueOf(distance);
Log.i("testing0" , testing);
distance = rad2deg(distance);
distance = distance *60 * 1.1515 * 1.609344; //distance in km
String distances = String.valueOf(distance);
Log.i("distance = ", distances);
Toast.makeText(this, "Distance = " + distances, Toast.LENGTH_SHORT).show();
}
Now I am sure that I am success to get the latitude and longitude of two places from Firebase. However, I dont know why I keep get the result of NaN for the calculation. Guys, please help.
use this function for calculating the distance of two location. I used that in my last project and I'm sure about that:
public static double calculateDistance(LatLng pointA, LatLng pointB) {
double earthRadius = 6371;
double latDiff = Math.toRadians(pointB.getLatitude() - pointA.getLatitude());
double lngDiff = Math.toRadians(pointB.getLongitude() - pointA.getLongitude());
double a = Math.sin(latDiff / 2) * Math.sin(latDiff / 2) +
Math.cos(Math.toRadians(pointA.getLatitude())) *
Math.cos(Math.toRadians(pointB.getLatitude())) *
Math.sin(lngDiff / 2) * Math.sin(lngDiff / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = earthRadius * c;
int meterConversion = 1000;
return distance * meterConversion;
}

Distance calculation bug android

Hi I have been doing the app for calculating the distance and speed of travelling. All the function of getting speed and distance working fine, however during the testing I saw the bug where the distance is getting started to be measured only if the speed is 19 Km/h +
Would anybody have any idea why this might be happening ?
Thanks
//initialize location listener
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
getSpeed(location);
getDistance(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
//get the speed from the given location updates
public void getSpeed(Location location) {
currentSpeed = (location.getSpeed() * 3600 / 1000);
String convertedSpeed = String.format("%.2f", currentSpeed);
speedTxt.setText(convertedSpeed + "Km/h");
}
private void getDistance(Location location) {
//to capture current location and keep as starting position of person
if (pLat == 500.0 && pLng == 500.0 ){
pLat = location.getLatitude();
pLng = location.getLongitude();
}
if (cLat == 500.0 && cLng == 500.0){
cLat = location.getLatitude();
cLng=location.getLongitude();
}
//to check is the person has changed location
if (pLat != cLat && pLng != cLng) {
pLat = cLat;
pLng = cLng;
}
//update the current location
cLat = location.getLatitude();
cLng = location.getLongitude();
//call the calculation method
distance += getDistanceBetweenGeoPoints(cLat, cLng, pLat, pLng);
String convertedDistance = String.format("%.2f", distance);
distanceTxt.setText(" " + convertedDistance);
}
public double getDistanceBetweenGeoPoints(Double cLat, Double cLng, Double pLat, Double pLng) {
// CALCULATE DISTANCE BETWEEN TWO POINTS
double earthRadius = 6367; //meters
double dLat = Math.toRadians(cLat - pLat);
double dLng = Math.toRadians(cLng - pLng);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(cLat)) * Math.cos(Math.toRadians(pLat)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = (double) (earthRadius * c);
dist = Math.round(dist * 100) / 100.0;
return dist;
}
};
Your getDistanceBetweenGeoPoints function is going to return exactly 0 for small differences in location because of this line:
dist = Math.round(dist * 100) / 100.0;
Try rounding the total distance only for display purposes in GetDistance():
//call the calculation method
distance += getDistanceBetweenGeoPoints(cLat, cLng, pLat, pLng);
String convertedDistance = String.format("%.2f", Math.round(dist * 100) / 100.0);
distanceTxt.setText(" " + convertedDistance);
private void getDistance(Location location) {
//to capture current location and keep as starting position of person
if (pLat == 500.0 && pLng == 500.0) {
pLat = location.getLatitude();
pLng = location.getLongitude();
}
if (cLat == 500.0 && cLng == 500.0) {
cLat = location.getLatitude();
cLng = location.getLongitude();
}
//to check is the person has changed location
if (pLat != cLat && pLng != cLng) {
pLat = cLat;
pLng = cLng;
}
//update the current location
cLat = location.getLatitude();
cLng = location.getLongitude();
//call the calculation method
distance += getDistanceBetweenGeoPoints(cLat, cLng, pLat, pLng);
//String convertedDistance = String.format("%.2f", distance);
String convertedDistance = String.format("%.2f", Math.round(distance * 100) / 100.0);
distanceTxt.setText(" " + convertedDistance);
}
public double getDistanceBetweenGeoPoints(Double cLat, Double cLng, Double pLat, Double pLng) {
// CALCULATE DISTANCE BETWEEN TWO POINTS
double earthRadius = 6367; //meters
double dLat = Math.toRadians(cLat - pLat);
double dLng = Math.toRadians(cLng - pLng);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(Math.toRadians(cLat)) * Math.cos(Math.toRadians(pLat)) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double dist = (double) (earthRadius * c);
//dist = Math.round(dist * 100) / 100.0;
return dist;
}

intelligent calculating distance between two geo locations in android

Look at this example:
public void start(){
//...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEN_SECONDS, TEN_METERS, this);
}
#Override
public void onLocationChanged(Location location) {
if(location.distanceTo(_lastLocation) > TEN_KM_IN_METERS){
actionA(location);
_lastLocation = location;
} else {
actionB(location);
}
}
The implementation of Location#distanceTo(l) is pretty complicated and CPU-intensive. So i don't want to call this operation on every location update.
Question: is it any proper way to avoid unnecessary Location#distanceTo(l) calls
What i tried so far. According Wiki - Decimal degrees i do it that way:
private boolean closeTogether(Location a, Location b) {
double changeLat = Math.abs(a.getLatitude() - b.getLatitude());
final float myNaiveMax = 0.005;
if (changeLat > myNaiveMax) {
return false;
}
double changeLon = Math.abs(a.getLongitude() - b.getLongitude());
if (changeLon > myNaiveMax) {
return false;
}
return true;
}
#Override
public void onLocationChanged(Location location) {
if(!closeTogether(location, _lastLocation) && location.distanceTo(_lastLocation) > TEN_KM_IN_METERS){
actionA(location);
_lastLocation = location;
} else {
actionB(location);
}
}
I've found that the Haversine formula is very good for this. Works well for my delivery tracking application. Here's how I calculate the distance between two points. Should get you started :)
/**
* getDistanceBetweenTwoPoints
* #param p1 - First point
* #param p2 - Second point
* #return distance between the two specified points (as the crow flys)
*/
public static double getDistanceBetweenTwoPoints(PointF p1, PointF p2) {
double R = 6371000; // Earth radius
double dLat = Math.toRadians(p2.x - p1.x);
double dLon = Math.toRadians(p2.y - p1.y);
double lat1 = Math.toRadians(p1.x);
double lat2 = Math.toRadians(p2.x);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2)
* Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = R * c;
return d;
}
Edit And another
public static PointF calculateDerivedPosition(PointF point,
double range, double bearing)
{
double EarthRadius = 6371000; // m
double latA = Math.toRadians(point.x);
double lonA = Math.toRadians(point.y);
double angularDistance = range / EarthRadius;
double trueCourse = Math.toRadians(bearing);
double lat = Math.asin(Math.sin(latA) * Math.cos(angularDistance) +
Math.cos(latA) * Math.sin(angularDistance) * Math.cos(trueCourse));
double dlon = Math.atan2(Math.sin(trueCourse) * Math.sin(angularDistance) * Math.cos(latA),
Math.cos(angularDistance) - Math.sin(latA) * Math.sin(lat));
double lon = ((lonA + dlon + Math.PI) % (Math.PI * 2)) - Math.PI;
lat = Math.toDegrees(lat);
lon = Math.toDegrees(lon);
PointF newPoint = new PointF((float) lat, (float) lon);
return newPoint;
}

Calculate distance using latitude and longitude using gps data .

I am trying to calculate distance using gps lat and long data.
but i can't get accurate result .when i am given a static data ,then distance formula work perfect ,
public class NWDService extends Service implements LocationListener {
private LocationManager myLocationManager;
private LocationProvider myLocationProvider;
NotificationManager myNotificationManager;
private long frequency;
private Handler handler;
private double total_distance = 0;
private Location currentLocation;
public void onLocationChanged(Location newLocation) {
try {
System.out.println("latitude current :"+currentLocation.getLatitude());
System.out.println("latitude current :"+currentLocation.getLongitude());
System.out.println("latitude new :"+newLocation.getLatitude());
System.out.println("latitude new :"+newLocation.getLongitude());
System.out.println("distance total :"+total_distance);
//System.out.println(distance(22.306813, 73.180239,22.301016, 73.177986, 'K') + " Kilometers\n");
double diff = 0.0;
diff = currentLocation.getLatitude()- newLocation.getLatitude();
System.out.println("difference ::"+diff);
if(diff != 0){
total_distance = total_distance + distance(currentLocation.getLatitude(), currentLocation.getLongitude(), newLocation.getLatitude(), newLocation.getLatitude(), 'K');
//total_distance = distance(22.307309,73.181098,23.030000,72.580000,'K');
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Total Distance:"+total_distance, Toast.LENGTH_LONG).show();
}
});
}
currentLocation = newLocation;
} catch (Exception e) {
currentLocation = newLocation;
e.printStackTrace();
}
}
private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
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;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts decimal degrees to radians :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
/*:: This function converts radians to decimal degrees :*/
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
private void myNotify(String text) {
Notification notif = new Notification(R.drawable.ic_launcher, text, System
.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Home.class), 0);
notif.setLatestEventInfo(this, "NotWhileDriving", text, contentIntent);
// notif.defaults = Notification.DEFAULT_VIBRATE;
myNotificationManager.notify((int) System.currentTimeMillis(), notif);
}
#Override
public void onCreate() {
super.onCreate();
handler = new Handler();
android.util.Log.d("NWD", "creating");
myLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
System.out.println("location manager:"+myLocationManager.getAllProviders());
myLocationProvider = myLocationManager.getProvider("gps");
myNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
updatePreferences();
}
public void updatePreferences() {
// sync local variables with preferences
android.util.Log.d("NWD", "updating preferences");
frequency = 10;
// update the LM with the new frequency
myLocationManager.removeUpdates(this);
myLocationManager.requestLocationUpdates(myLocationProvider.getName(),frequency, 0, this);
}
#Override
public void onDestroy() {
super.onDestroy();
android.util.Log.d("NWD", "destroying");
myLocationManager.removeUpdates(this);
myNotify("stopping");
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
android.util.Log.d("NWD", "starting");
currentLocation = myLocationManager
.getLastKnownLocation(myLocationProvider.getName());
myNotify("starting");
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
#Override
public IBinder onBind(Intent arg0) {
return null; // this is for heavy IPC, not used
}
}
Please help me what is the problem in my code...
Just use Location.distanceTo(Location) it will give you a really distance between two different Locations.
First, I don't believe this code works on different parts of the earth. I don't see the WGS 84 parameters, only some magic numbers in
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
Where did you get that from? Do you understand it?
Second, if your data is noisy, you're adding up this noise by summing totalDistance. You might want to check if the distance is above some threshold and only add totalDistance if the distance threshold is exceeded.
You can use Google Distance matrix API for find accurate result of distance between two place.
for detail study you can refer from:
https://developers.google.com/maps/documentation/distancematrix/

How to calculate distance between two locations using their longitude and latitude value

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;
There is an android.location.Location.distanceBetween() method which does this quite well.
Android Developer Docs: Location
Here getting distance in miles (mi)
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);
}
Try this code.
startPoint.distanceTo(endPoint) function returns the distance between those places in meters.
Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);
Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);
double distance=startPoint.distanceTo(endPoint);
here "distance" is our required result in Meters. I hope it will work for android.
in build.gradle:
compile 'com.google.maps.android:android-maps-utils:0.4'
and then:
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
return SphericalUtil.computeDistanceBetween(point1, point2);
}
If you have two Location Objects Location loc1 and Location loc2 you do
float distance = loc1.distanceTo(loc2);
If you have longitude and latitude values you use the static distanceBetween() function
float[] results = new float[1];
Location.distanceBetween(startLatitude, startLongitude,
endLatitude, endLongitude, results);
float distance = results[0];
private String getDistanceOnRoad(double latitude, double longitude,
double prelatitute, double prelongitude) {
String result_in_kms = "";
String url = "http://maps.google.com/maps/api/directions/xml?origin="
+ latitude + "," + longitude + "&destination=" + prelatitute
+ "," + prelongitude + "&sensor=false&units=metric";
String tag[] = { "text" };
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream is = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(is);
if (doc != null) {
NodeList nl;
ArrayList args = new ArrayList();
for (String s : tag) {
nl = doc.getElementsByTagName(s);
if (nl.getLength() > 0) {
Node node = nl.item(nl.getLength() - 1);
args.add(node.getTextContent());
} else {
args.add(" - ");
}
}
result_in_kms = String.format("%s", args.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
return result_in_kms;
}
In Kotlin
private fun distanceInMeter(startLat: Double, startLon: Double, endLat: Double, endLon: Double): Float {
var results = FloatArray(1)
Location.distanceBetween(startLat,startLon,endLat,endLon,results)
return results[0]
}
private float distanceFrom_in_Km(float lat1, float lng1, float lat2, float lng2) {
if (lat1== null || lng1== null || lat2== null || lng2== null)
{
return null;
}
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Use the below method for calculating the distance of two different locations.
public double getKilometers(double lat1, double long1, double lat2, double long2) {
double PI_RAD = Math.PI / 180.0;
double phi1 = lat1 * PI_RAD;
double phi2 = lat2 * PI_RAD;
double lam1 = long1 * PI_RAD;
double lam2 = long2 * PI_RAD;
return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));}
Try This below method code to get the distance in meter between two location, hope it will help for you
public static double distance(LatLng start, LatLng end){
try {
Location location1 = new Location("locationA");
location1.setLatitude(start.latitude);
location1.setLongitude(start.longitude);
Location location2 = new Location("locationB");
location2.setLatitude(end.latitude);
location2.setLongitude(end.longitude);
double distance = location1.distanceTo(location2);
return distance;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
Why are you writing the code for calculating the distance by yourself?
Check the api's in Location class
You should use Haversine Distance Formulas
Haversine Formulas used to calculate the great distance between two points on the earth.
public void haversine(double lat1, double lon1, double lat2, double lon2) {
double Rad = 6372.8; //Earth's Radius In kilometers
// TODO Auto-generated method stub
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
haverdistanceKM = Rad * c;
}
Updated on October 8, 2021
Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.
Java
public float getDistance(double startLat,double startLang,double endLat,double endLang) {
Location locStart = new Location("");
locStart.setLatitude(startLat);
locStart.setLongitude(startLang);
Location locEnd = new Location("");
locEnd.setLatitude(endLat);
locEnd.setLongitude(endLang);
return locStart.distanceTo(locEnd);
}
Kotlin
private fun getDistance(
startLat: Double,
startLang: Double,
endLat: Double,
endLang: Double
): Float {
val locStart = Location("")
locStart.latitude = startLat
locStart.longitude = startLang
val locEnd = Location("")
locEnd.latitude = endLat
locEnd.longitude = endLang
return locStart.distanceTo(locEnd)
}
Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.
public float getMesureLatLang(double lat,double lang) {
Location loc1 = new Location("");
loc1.setLatitude(getLatitute());// current latitude
loc1.setLongitude(getLangitute());//current Longitude
Location loc2 = new Location("");
loc2.setLatitude(lat);
loc2.setLongitude(lang);
return loc1.distanceTo(loc2);
// return distance(getLatitute(),getLangitute(),lat,lang);
}

Categories

Resources