我正在开发一个应用程序,它更像是您朋友之间的时移竞赛。
我需要计算移动车辆的速度,我不想使用Location.getSpeed()
方法。(在底部详细解释了为什么我不想使用它)
我正在尝试借助可用的纬度和经度来计算速度,这就是我需要帮助的地方。
需要的帮助:我想知道的是:
- 如果算法正确
- 我应该用厘米而不是米来计算吗
- 如果有任何可用的代码/库可以做到这一点。
我正在使用以下代码:
这给了我两个 LatLng 点之间的距离:
long getDistanceBetweenPoints(double lat1, double lng1, double lat2, double lng2 ){
double dLat = Math.toRadians(lat2 - lat1);
double dLon = 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(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
long distanceInMeters = Math.round(6371000 * c);
return distanceInMeters;
}
以下代码是它的使用方式:
if(lastLat == -1 && lastLng == -1){
lastLat = location.getLatitude();
lastLng = location.getLongitude();
lastTimeStamp = location.getTime();
return;
}
long distanceInMeters = getDistanceBetweenPointsAndSetTotal(lastLat, lastLng, location.getLatitude(), location.getLongitude());
long timeDelta = (location.getTime() - lastTimeStamp)/1000;
long speed = 0;
if(timeDelta > 0){
speed = (distanceInMeters/timeDelta);
}
Log.d("Calculations","Distance: "+distanceInMeters+", TimeDelta: "+timeDelta+" seconds"+",speed: "+speed+" Accuracy: "+location.getAccuracy());
lastLat = location.getLatitude();
lastLng = location.getLongitude();
lastTimeStamp = location.getTime();
当我运行它时,我从该 LogCat 获得以下输出:
Distance: 0, TimeDelta: 0 seconds,speed: 0 Accuracy: 5.0
详细原因
目标消费者不应该拥有带有高质量 GPS 芯片的高质量设备,因此在设备移动时始终获得非常准确的定位是不可能的。
因此我不想依赖这种Location.getSpeed()
方法,因为我观察到它仅在精度在 5~8 米范围内时才会给出速度值。
在一般情况下,我得到的正常精度范围是 10-15 米,并且getSpeed()
没有给出任何速度。甚至hasSpeed()
开始返回错误。
我已经在这件事上琢磨了三天多,对此的任何帮助将不胜感激。
非常感谢提前!