我已经在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 :(得分:0)
就像你从json返回的距离对象中取出一样,你必须获取持续时间对象 JSONObject duration = steps.getJSONObject(" duration");
您还可以通过在您的网址中传递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