在这个回答中,我将展示两种获取当前速度的主要方法。一种是使用位置服务(location.getSpeed()),另一种是老派的手动计算速度版本。
首先定义三个主要的全局变量。
double curTime= 0
double oldLat = 0.0
double oldLon = 0.0
现在转到您的onLocationChanged方法,并在其中调用此方法,
getspeed(location)
现在让我们实现 getSpeed 方法
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();
}
}
好的,我们已经完成了这个步骤,现在需要实现calculationBydistance方法。
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;
}
在这个else部分,速度将以m /毫秒的形式显示,你可以将其转换为秒...然后我们就完成了。
location.distanceTo(Location)
来获取距离? - Renan Bandeira