我最近一直在尝试获取用户的速度。
我已经知道了这两个点的位置和时间,但似乎我只是找到了计算速度的正确方法,尽管尝试了很多次。
这就是我现在正在尝试的:
public void onLocationChanged(Location location) {
Toast.makeText(this, "Location Changed", Toast.LENGTH_SHORT).show();
if (settings == null) {
settings = getSharedPreferences(PREFS_NAME, 0);
}
int ExceedingLimit = settings.getInt("ExceedLimit", 10);
int LowerLimit = settings.getInt("LowerLimit", 2);
int UpperLimit = settings.getInt("UpperLimit", 12);
double speed = 0;
if (location != null) {
double calc_long = Math.pow(location.getLongitude() - OldLocation.getLongitude(), 2);
double calc_lat = Math.pow(location.getLatitude() - OldLocation.getLatitude(), 2);
double time = (double) location.getTime() - (double) OldLocation.getTime();
speed = Math.sqrt(calc_long + calc_lat) / time;
}
if (location != null && location.hasSpeed()) {
speed = location.getSpeed();
}
if (LowerLimit < speed && speed < UpperLimit) {
ExceedInstance += 1;
}
OldLocation = location;它似乎不工作,因为它保持在零,即使在移动。
我在这里初始化旧位置:
public void onConnected(Bundle connectionHint) {
Toast.makeText(this, "You have connected", Toast.LENGTH_LONG).show();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(UPDATE_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mLocationClient, mLocationSettingsRequest
);
result.setResultCallback(ViewingWindow.this);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, mLocationRequest, this);
OldLocation = LocationServices.FusedLocationApi.getLastLocation(mLocationClient);
}
}我还试图分别计算这两个数,并将它们相除,但最终是一个强制转换错误,它仍然保持为零。
强制转换也不起作用。当我将其转换为双倍时,它给出了E-10到E-11的数字,低得离谱,但每次位置更新时仍在变化。
问题是,即使我移动的时候,速度也不会去,但是。
我真的不知道为什么这些都是错的。有人能帮我吗?
发布于 2016-08-01 17:11:11
你有没有尝试将所需的时间增加一倍?
speed = (double)Math.sqrt(
Math.pow(location.getLongitude() - OldLocation.getLongitude(), 2)
+ Math.pow(location.getLatitude() - OldLocation.getLatitude(), 2)
) / (double)(location.getTime() - OldLocation.getTime());因为我不知道Math.sqrt()返回什么。它可能返回一个浮点数,因为它的计算速度要快得多。
如果您的速度不是很高,您也可以将速度变量更改为浮点。
发布于 2016-08-01 18:02:45
尝尝这个
double calc_long = Math.pow(location.getLongitude() - OldLocation.getLongitude(), 2);
double calc_lat = Math.pow(location.getLatitude() - OldLocation.getLatitude(), 2);
double time = location.getTime() - OldLocation.getTime();
speed = (double) Math.sqrt(calc_long + calc_lat) / time;另外,如何测试速度?根据我的经验,经度和纬度需要几秒钟来更新和注册任何移动,所以如果你试图保持一个恒定的速度大约一分钟(无论如何),它应该触发速度计。
https://stackoverflow.com/questions/38694787
复制相似问题