I am working on app and try to get the speed and distance travelled by the user. I have used Google Play services location class to get the speed but it always returns me 0.
in this answer im gonna show you two main path to get current speed.one is by using location service (location.getSpeed()) and other one is old school manually calculate speed version.
first define three main global variables
double curTime= 0;
double oldLat = 0.0;
double oldLon = 0.0;
now move on to your onLocationChannged method and inside it call to this method,
getspeed(location);
now lets implement getSpeed method
private void getspeed(Location location){
double newTime= System.currentTimeMillis();
double newLat = location.getLatitude();
double newLon = location.getLongitude();
if(location.hasSpeed()){
float speed = location.getSpeed();
Toast.makeText(getApplication(),"SPEED : "+String.valueOf(speed)+"m/s",Toast.LENGTH_SHORT).show();
} else {
double distance = calculationBydistance(newLat,newLon,oldLat,oldLon);
double timeDifferent = newTime - curTime;
double speed = distance/timeDifferent;
curTime = newTime;
oldLat = newLat;
oldLon = newLon;
Toast.makeText(getApplication(),"SPEED 2 : "+String.valueOf(speed)+"m/s",Toast.LENGTH_SHORT).show();
}
}
ok we are done with it, and now implement calculationBydistance method
public double calculationBydistance(double lat1, double lon1, double lat2, double lon2){
double radius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return radius * c;
}
in here else part the speed will comes in m/miliseconds you can convert it to seconds...and we are done