Reputation: 989
I wanted to update the server with latlong of current location when there is difference of x meters between current location and previous location.
I have a app where i wanted to track vehicle movement so the driver who is using that app inside the vehicle will automatically update its current location when there is difference of x meters between current position of cab and previously stored location. So other users will be able to locate this driver where exactly is.(So in this case should i run a thread to automatically request for update of current location or something).
How to find out if the distance between two latlong points so that i can find out if the difference between current location and previously stored location is X meters.
If i use requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)
function i will be able to provide minDistance as X meters and it would do the job but it is not giving accurate update to server.
I have gone through this question here but as i am a beginner did not have clear idea. So i would appreciate if somebody helps how i can achieve this.
Upvotes: 1
Views: 654
Reputation: 4221
You can use the Google Play Services Location API. Read the documentation about how to recive location updates here.
When creating a LocationRequest
you can specify how often you want to receive the updates using setInterval
and setFastestInterval
or the minimum distance between updates using setSmallestDisplayments
.
When you receive an update you can store the latitude and longitude in shared preferences and use those values the next time you receive an update.
If you want to check if the distance between the two locations is greater than the minimum distance you specified you can do so using Location.distanceBetween
.
For information on how to save the location data in shared preferences see this answer.
Upvotes: 2
Reputation: 41
You can store the previous location in a preference variable and then whenever the location changes you calculate distance between current and previous location, for that you can use the distanceBetween function in your LocationListener :
@Override
public void onLocationChanged(Location loc) {
....
final float[] results = new float[1];
Location.distanceBetween(previous.lat, previous.lng, loc.lat, loc.lng, results);
...
}
And now you have the distance in meter stored in results[0] and you can do with it whatever you want.
Upvotes: 1