试图将LatLng数组的距离相加

时间:2014-12-02 17:32:19

标签: android

我试图总结LatLng数组之间的总距离,但是很难。这是我到目前为止所得到的:

private double sumDistance() {
    Location loc = new Location("distance provider");
    double previousLatitude;
    double previousLongitude;
    float[] results = new float[1];
    for (LatLng latLng : mMapList) {
        previousLatitude = latLng.latitude;
        previousLongitude = latLng.longitude;
        loc.distanceBetween(previousLatitude, previousLongitude, latLng.latitude, latLng.longitude, results);
    }
    return 0;
}

这个问题是两者的latlng是相同的。有什么方法可以让我以前的latlng或更清洁的方式做到这一点,我没想到?

2 个答案:

答案 0 :(得分:4)

为什么在计算距离后不指定“上一个变量”?这样的事情应该有效

private double sumDistance() {
    Location loc = new Location("distance provider");
    double previousLatitude = mMapList.get(0).latitude;
    double previousLongitude = mMapList.get(0).longitude;
    float[] results;
    for (int i=1;i<mMapList.size();i++) {
        loc.distanceBetween(previousLatitude, previousLongitude, mMapList.get(i).latitude, mMapList.get(i).longitude, results);
        previousLatitude = mMapList[i].latitude;
        previousLongitude = mMapList[i].longitude;
    }
    return 0;
}

答案 1 :(得分:1)

double previousLatitude;
double previousLongitude;
float[] results;
for (int i=0; i<mMapList.size(); ++i) {
    LatLng latLng = mMapList.get(i);
    if (i == 0) {
        // Previous weren't set yet, nothing to measure
        // Set them and skip loop
        previousLatitude = latLng.latitude;
        previousLongitude = latLng.longitude;
        continue;
    }

    // Measure previous with current
    loc.distanceBetween(previousLatitude, previousLongitude, latLng.latitude, latLng.longitude, results);
    // ~ Use the distance

    // Modify the previous ones
    previousLatitude = latLng.latitude;
    previousLongitude = latLng.longitude;
}