【问题标题】:Directions API total distance & duration with waypointsDirections API 总距离和航点持续时间
【发布时间】:2015-07-31 07:24:32
【问题描述】:

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

示例:从 Direction 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分钟

【问题讨论】:

  • 是的,您解析响应,获取每个项目并加上它们。你遇到过这个问题吗?
  • @Yurets 很好,我可以做距离,但是我如何计算持续时间,因为它可以是不同的格式?例如分钟,小时,天,它表示为人类可读的文本?愿意提供一些样品吗?

标签: android google-maps google-maps-android-api-2 driving-directions


【解决方案1】:

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

    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.

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

【讨论】:

  • 这就是我要找的。非常感谢。我一定会试试这个,让你知道它是怎么回事。干杯!
  • 好的,等会,愉快的编码:)
  • 代码中有问题,我能够修复它。假设旅程恰好需要 1 小时或 1 分钟或 1 天,则用于检查单日/小时/分钟的 if 语句将不会被执行,因为不会有尾随空格。例如,它将是“1 分钟”而不是“1 分钟”。我刚刚从 if-else 语句中删除了尾随空格并颠倒了顺序,因此它首先检查复数,然后检查单数,它工作正常。
  • 为什么不用duration的value字段呢? value 是持续时间是秒,所以只需总结所有这些以获得总秒数,然后根据需要对其进行格式化。查看我的答案以获取更多信息。
【解决方案2】:

这增加了库沙尔回答的持续时间:

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");
}

【讨论】:

    【解决方案3】:

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

       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);
    }
    

    【讨论】:

    • 持续时间呢?
    【解决方案4】:
    【解决方案5】:

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

    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;
    }
    

    【讨论】:

      【解决方案6】:

      这是我的代码。传递从方向请求 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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-15
        • 2020-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多