2017-05-13 6 views
1

私はすでに距離を取得するためにStackOverflowで答えを見つけましたが、移動時間を得るためにこれにどのようなコードを組み込むのか分かりません。ある場所から別の場所への移動時間を計算したい

public String getDistance(final double lat1, final double lon1, final double lat2, final double lon2){ 
     final String[] parsedDistance = new String[1]; 
     final String[] response = new String[1]; 
     Thread thread=new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 

        URL url = new URL("http://maps.googleapis.com/maps/api/directions/json?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric&mode=driving"); 
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
        conn.setRequestMethod("POST"); 
        InputStream in = new BufferedInputStream(conn.getInputStream()); 
        response[0] = org.apache.commons.io.IOUtils.toString(in, "UTF-8"); 

        JSONObject jsonObject = new JSONObject(response[0]); 
        JSONArray array = jsonObject.getJSONArray("routes"); 
        JSONObject routes = array.getJSONObject(0); 
        JSONArray legs = routes.getJSONArray("legs"); 
        JSONObject steps = legs.getJSONObject(0); 
        JSONObject distance = steps.getJSONObject("distance"); 
        parsedDistance[0] =distance.getString("text"); 

       } catch (ProtocolException e) { 
        e.printStackTrace(); 
       } catch (MalformedURLException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
     thread.start(); 
     try { 
      thread.join(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     Log.v("HomeMapsActivity", "This is the parsed distance "+parsedDistance); 
     return parsedDistance[0]; 


    } 
+0

S/stackoverflowの/ StackOverflowの/ – Eefret

答えて

0

jsonが返した距離オブジェクトをフェッチしたように、デュレーションオブジェクトをフェッチする必要があります。
JSONObject duration = steps.getJSONObject( "duration");

ます。また、このようなあなたのURLにtraffic_modelとdeparture_timeのパラメータを渡すことによって、現在の交通状況を考慮期間を得ることができます -
traffic_model = best_guess & departure_timeの=今

をしてから返されたJSONからduration_in_trafficオブジェクトをフェッチ
JSONObject duration = steps.getJSONObject( "duration_in_traffic");

はこちらをご覧ください - https://developers.google.com/maps/documentation/directions/intro#TravelModes

+0

を私はあなたが言っただけで何をしたが、私は期間中に任意の値を取得していないです! –

関連する問題