Cómo obtener distancia de Google Direction API en Android

http://maps.googleapis.com/maps/api/directions/json?origin=-20.291825,57.448668&destination=-20.179724,57.613463&sensor=false&mode=%22DRIVING%22

Por ejemplo, este enlace genera lo siguiente:

"routes" : [ { "bounds" : { "northeast" : { "lat" : -20.1765204, "lng" : 57.6137001 }, "southwest" : { "lat" : -20.2921672, "lng" : 57.4472155 } }, "copyrights" : "Map data ©2014 Google", "legs" : [ { "distance" : { "text" : "24.6 km", "value" : 24628 }, 

Quiero extraer sólo la distancia y mostrarlo en android

Para obtener una distancia desde un Google Maps, puede utilizar la API de Google y el analizador JSON para recuperar el valor de la distancia.

Método de muestra

 private double getDistanceInfo(double lat1, double lng1, String destinationAddress) { StringBuilder stringBuilder = new StringBuilder(); Double dist = 0.0; try { destinationAddress = destinationAddress.replaceAll(" ","%20"); String url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + latFrom + "," + lngFrom + "&destination=" + latTo + "," + lngTo + "&mode=driving&sensor=false"; HttpPost httppost = new HttpPost(url); HttpClient client = new DefaultHttpClient(); HttpResponse response; stringBuilder = new StringBuilder(); response = client.execute(httppost); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); int b; while ((b = stream.read()) != -1) { stringBuilder.append((char) b); } } catch (ClientProtocolException e) { } catch (IOException e) { } JSONObject jsonObject = new JSONObject(); try { jsonObject = new JSONObject(stringBuilder.toString()); 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"); Log.i("Distance", distance.toString()); dist = Double.parseDouble(distance.getString("text").replaceAll("[^\\.0123456789]","") ); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return dist; } 

Para obtener detalles sobre los parámetros y más detalles sobre las diferentes opciones disponibles, consulte esto.

https://developers.google.com/maps/documentation/directions/

Sólo marque debajo del enlace. Probablemente obtendrá idea de ello y probarlo por su cuenta.

http://about-android.blogspot.in/2010/03/sample-google-map-driving-direction.html

También puede utilizar Google Distance Matrix API

https://developers.google.com/maps/documentation/distancematrix/

 public class ApiDirectionsAsyncTask extends AsyncTask<URL, Integer, StringBuilder> { private static final String TAG = makeLogTag(ApiDirectionsAsyncTask.class); private static final String DIRECTIONS_API_BASE = "https://maps.googleapis.com/maps/api/directions"; private static final String OUT_JSON = "/json"; // API KEY of the project Google Map Api For work private static final String API_KEY = "YOUR_API_KEY"; @Override protected StringBuilder doInBackground(URL... params) { Log.i(TAG, "doInBackground of ApiDirectionsAsyncTask"); HttpURLConnection mUrlConnection = null; StringBuilder mJsonResults = new StringBuilder(); try { StringBuilder sb = new StringBuilder(DIRECTIONS_API_BASE + OUT_JSON); sb.append("?origin=" + URLEncoder.encode("Your origin address", "utf8")); sb.append("&destination=" + URLEncoder.encode("Your destination address", "utf8")); sb.append("&key=" + API_KEY); URL url = new URL(sb.toString()); mUrlConnection = (HttpURLConnection) url.openConnection(); InputStreamReader in = new InputStreamReader(mUrlConnection.getInputStream()); // Load the results into a StringBuilder int read; char[] buff = new char[1024]; while ((read = in.read(buff)) != -1){ mJsonResults.append(buff, 0, read); } } catch (MalformedURLException e) { Log.e(TAG, "Error processing Distance Matrix API URL"); return null; } catch (IOException e) { System.out.println("Error connecting to Distance Matrix"); return null; } finally { if (mUrlConnection != null) { mUrlConnection.disconnect(); } } return mJsonResults; } } 

Espero que te ayude!

  • Calcular la distancia entre dos ubicaciones geográficas
  • ¿Es posible obtener distancia entre la ubicación actual y una calle, avenida o zona?
  • mapa androide de google que encuentra la distancia
  • La distancia entre dos ubicaciones no es correcta
  • Creación de un objeto Ubicación en Android con valores de latitud y longitud
  • ¿Es posible medir la distancia al objeto con la cámara?
  • Medición de distancia con sensor láser IR Nexus 6P y 5X
  • Lista de ordenación de los puntos lon \ lat, comience con los puntos más cercanos
  • ¿Cómo calcular la distancia entre dos dispositivos Android? (Bluetooth preferido)
  • Android - ¿Cómo obtener el tiempo estimado de conducción de un lugar a otro?
  • Distancias de enfoque de la cámara
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.