String url = getDirectionsUrl(pickupLatLng, dropLatLng);
new GetDisDur().execute(url);
使用 latlng 创建 URL
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String mode = "mode=driving";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + mode;
String output = "json";
return "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
}
类GetDisDur
private class GetDisDur extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject routes1 = routes.getJSONObject(0);
JSONArray legs = routes1.getJSONArray("legs");
JSONObject legs1 = legs.getJSONObject(0);
JSONObject distance = legs1.getJSONObject("distance");
JSONObject duration = legs1.getJSONObject("duration");
distanceText = distance.getString("text");
durationText = duration.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
}
}