我正在构建一个跟踪我的跑步和行走的应用程序,但我在计算总距离时遇到了一些麻烦。
这是我的代码的一部分,我在其中获取纬度和经度的值以及计算距离的地方。
public class SportsActicity {
protected Integer userId;
protected ArrayList<Position> route = new ArrayList<Position>();
public SportsActicity() {
this.userId = 1;
}
public void track(Double latitude, Double longitude, Double altitude, float speed, long chron) {
Date currentDate = new Date();
Position currentPosition = new Position(currentDate, latitude, longitude, altitude, speed, chron);
route.add(currentPosition);
// Float velocidade = (locat.getSpeed()*3600)/1000;
}
public double getTotalDistance() {
double distance = 0;
if(route.size() > 1) {
for (Integer i = 0; i < route.size() - 1; i++) {
distance += test(route.get(i).latitude, route.get(i).longitude, route.get(i + 1).latitude, route.get(i + 1).longitude);
}
}
return distance;
}
public Float test(Double lat1, Double lon1, Double lat2, Double lon2) {
double earthRadius = 6371;
double latDiff = Math.toRadians(lat2-lat1);
double lngDiff = Math.toRadians(lon2-lon1);
double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
Math.cos(Math.toRadians(lat1))*
Math.cos(Math.toRadians(lat2))* Math.sin(lngDiff /2) *
Math.sin(lngDiff /2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = earthRadius * c;
int meterConversion = 1609;
return new Float(distance * meterConversion).floatValue();
}
如果我不移动,总距离总是在增加,大约 10(不知道它是否以米为单位),并且我得到的值看起来不正确。