路线 API 总距离和持续时间 waypoints

Directions API total distance & duration with waypoints

我在 Android 应用程序中从 Directions API 获取包括 waypoints 在内的路线。它包含多个 "leg" 段,它们有自己的距离和持续时间。有没有办法将所有距离和持续时间相加得到总值?

示例:从方向 API

剥离 json 线段
legs": [
{
  "distance": {
    "text": "389 km",
    "value": 389438
  },
  "duration": {
   "text": "6 hours 31 mins",
   "value": 23452
  }
},
{
  "distance": {
   "text": "0.5 km",
   "value": 487
  },
  "duration": {
   "text": "2 mins",
   "value": 102
  }
}
]

根据上面的回复,有没有办法计算和显示如下输出:

总距离:389.5公里 总时长:6 小时 33 分钟

此方法将计算所有腿数组的距离:

   public void parseJson(String json) {

    JSONObject jsonObj = new JSONObject(json);
    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();

    JSONObject legsJson = object.getJSONObject("legs");
    long dist = 0;
    for( int i = 0; i < legsJson.size(); i++ ) {
        // dist in meter
        dist = dist + jsonObj[i].getJSONArray("distance").getString("value");
    }

    // convert to killo meter
    float frac = dist % 1000;
    dist = dist / 1000 ;
    dist = dist + frac;
    Log.w("distance","Calculated distance :"+dist);
}

除了我对@Kushal 的评论和回答之外,还有一种计算总时间的方法。我跳过获取 JSONObject 的方法,因为它已经描述并给出了一个示例,其中给定的 String[] 是您在解析 JSON 时得到的。在这个例子中,我用给定的响应做了所有可能的场景,所以你可以在不修改的情况下使用它:

    String[] timeItems = {"4 days 1 hour 12 mins", "5 hours 9 mins"}; // as example for visibility
    int[] total = {0, 0, 0}; // days, hours, minutes
    for(int i = 0; i < timeItems.length; i++){
        if(timeItems[i].contains("day ")){
            total[0]++;
        }else if(timeItems[i].contains("days")){
            total[0] += Integer.valueOf(timeItems[i].substring(0, timeItems[i].indexOf(" days")));
        }
        if(timeItems[i].contains("hour ")){
            total[1]++;
        }else if(timeItems[i].contains("hours")){
            if(timeItems[i].indexOf(" hours") <= 3){
                total[1] += Integer.valueOf(timeItems[i].substring(0, timeItems[i].indexOf(" hours")));
            }else{
                if(timeItems[i].contains("days")){
                    total[1] += Integer.valueOf(timeItems[i].substring(timeItems[i].lastIndexOf("days ")) + 5, timeItems[i].indexOf(" hours"));
                }else{
                    total[1] += Integer.valueOf(timeItems[i].substring(timeItems[i].lastIndexOf("day ")) + 4, timeItems[i].indexOf(" hours"));
                }
            }
        }
        if(timeItems[i].contains("min ")){
            total[2]++;
        }else if(timeItems[i].contains("mins")){
            if(timeItems[i].indexOf(" mins") <= 3){
                total[2] += Integer.valueOf(timeItems[i].substring(0, timeItems[i].indexOf(" mins")));
            }else{
                if(timeItems[i].contains("hours")){
                    total[2] += Integer.valueOf(timeItems[i].substring(timeItems[i].indexOf("hours ") + 6, timeItems[i].indexOf(" mins")));
                }else{
                    total[2] += Integer.valueOf(timeItems[i].substring(timeItems[i].indexOf("hour ") + 5, timeItems[i].indexOf(" mins")));
                }
            }
        }
    }
    Log.d("LOG", total[0] + " days " + total[1] + " hours " + total[2] + " mins.");

这比我想象的要复杂一点,也许可以以某种方式简化或使用类似的想法,但重点是向您展示工作示例。我调试了这段代码。它给出正确的输出:

05-19 23:00:38.687  14251-14251/whatever.com.myapplication D/LOG﹕ 4 days 6 hours 21 mins.

希望对您有所帮助。 让我知道它是否适合你。

根据推荐路线估算行程时间和距离。

https://developers.google.com/maps/documentation/distance-matrix/

api https://maps.googleapis.com/maps/api/distancematrix/json?origins=48.9107372,24.6907184&destinations=48.9333618,24.7070269&mode=driving&language=en-EN

这会增加 Kushal 回答的持续时间:

public void parseJson(String json) {

    JSONObject jsonObj = new JSONObject(json);
    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();

    JSONObject legsJson = object.getJSONObject("legs");
    long totalDistance = 0;
    int totalSeconds = 0;
    for( int i = 0; i < legsJson.size(); i++ ) {
        // distance in meter
        totalDistance = totalDistance + Long.parseLong(jsonObj[i].getJSONArray("distance").getString("value"));
        totalSeconds = totalSeconds + Integer.parseInt(jsonObj[i].getJSONArray("duration").getString("value"));
    }

    // convert to kilometer
    double dist = dist / 1000.0 ;
    Log.d("distance", "Calculated distance:" + dist);

    int days = totalSeconds / 86400
    int hours = (totalSeconds - days * 86400) / 3600;
    int minutes = (totalSeconds - days * 86400 - hours * 3600) / 60;
    int seconds = totalSeconds - days * 86400 - hours * 3600 - minutes * 60;
    Log.d("duration", days + " days " + hours + " hours " + minutes + " mins" + seconds + " seconds");
}

距离计算方法。希望这会对某人有所帮助

private String distanceCalculation(String[] distanceItems) {
    //String[] totalDis = {"50 km", "4.5 km"}; // as example for visibility
    String totalDis = "";
    float distance = 0;
    String[] splitArray;
    if (distanceItems.length > 1) {
        for (String distanceItem : distanceItems) {
            splitArray = distanceItem.split(" ");
            Log.e("distance List", splitArray[0]);
            distance = distance + Float.valueOf(splitArray[0]);
        }
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        float twoDigitsF = Float.valueOf(decimalFormat.format(distance));
        totalDis = String.valueOf(twoDigitsF) + " km";
        Log.e("Total km ", totalDis);
    } else {
        totalDis = distanceItems[0];
    }
    return totalDis;
}

这是我的 code.Pass 从方向请求 url 获得的 JSONObject。

HashMap<String,Object> getDistanceDuration(JSONObject jsonObject) {
    HashMap<String,Object> hashMap=new HashMap<>();
    double totalDistance = 0;
    long totalDuration = 0;
    try {
        JSONArray jRoutes = jsonObject.getJSONArray("routes");
        for (int i = 0; i < jRoutes.length(); i++) {
            JSONArray jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
            for (int j = 0; j < jLegs.length(); j++) {
                JSONObject legs1 = jLegs.getJSONObject(j);
                JSONObject distance = legs1.getJSONObject("distance");
                JSONObject duration = legs1.getJSONObject("duration");
                totalDistance = totalDistance+distance.getLong("value");
                totalDuration = totalDuration+duration.getLong("value");
            }
        }
        totalDistance/=1000;
        totalDuration/=60;
        totalDistance= Math.round(totalDistance* 10) / 10.0;
        hashMap.put("distance",totalDistance);
        hashMap.put("duration",totalDuration);
        Log.i("distance",totalDistance);
        Log.i("duration",totalDuration);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return hashMap;
}