Я хочу получить расстояние по дороге пешком и на машине в своем приложении. У меня уже есть расстояние по линии, но теперь я хочу точное расстояние. Я прочитал, чтобы включить биллинг для учетной записи Google для ключа API, и я сделал это. Теперь я не мог понять код, который я видел несколько раз и пробовал их, но не могу понять, как использовать API, доступный в руководстве Google. Иногда приложение вылетает, а иногда ничего не дает в ответ. Приоритетно то, что я хочу сделать - это получить точное расстояние, которое может быть только пешком или на автомобиле. Любая помощь будет очень благодарна Последний код, который я пробовал, но он ничего не делает
origin = new LatLng(currentLat, currentLong);
dest = new LatLng(donarLat, donarLong);
String url = getDirectionsUrl();
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
private String getDirectionsUrl() {
// Origin of route
String str_origin = "origin=" + currentLat + "," + currentLong;
// Destination of route
String str_dest = "destination=" + donarLat + "," + donarLong;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String key = "key=" + "**********NR9TxLUwXyeq0jwV6k************";
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... urlList) {
try {
ArrayList<String> returnList = new ArrayList<String>();
for (String url : urlList) {
}
return returnList;
} catch (Exception e) {
Log.d("Background Task", e.toString());
return null; // Failed, return null
}
}
// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(ArrayList<String> results) {
super.onPostExecute(results);
ParserTask parserTask = new ParserTask();
for (String url : results) {
parserTask.execute(url);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, ArrayList<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
@Override
protected ArrayList<List<HashMap<String, String>>> doInBackground(String... jsonData) {
try {
ArrayList<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String, String>>>();
// for (String url : jsonData) {
for (int i = 0; i < jsonData.length; i++) {
JSONObject jObject = new JSONObject(jsonData[i]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = (ArrayList<List<HashMap<String, String>>>) parser.parse(jObject);
}
return routes;
} catch (Exception e) {
Log.d("Background task", e.toString());
return null; // Failed, return null
}
}
@Override
protected void onPostExecute(ArrayList<List<HashMap<String, String>>> result) {
if (result.size() < 1) {
Toast.makeText(DonarList.this, "No Points", Toast.LENGTH_LONG).show();
return;
}
for (int i = 0; i < result.size(); i++) {
List<HashMap<String, String>> path = result.get(i);
String distance = "No distance";
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) {
distance = point.get("distance");
continue;
}
}
Log.d("Distance: ", distance);
Toast.makeText(DonarList.this, "Your Distance ya hy :" + distance, Toast.LENGTH_SHORT).show();
}