2011-08-29 9 views
8

Sto cercando di utilizzare l'API di google maps per recuperare i tempi di direzione. Spero di creare un url, ottenere la risposta JSON e quindi esaminare quella risposta per la durata del viaggio. Dopo aver creato l'oggetto JSON, ho problemi a spostarlo. Per me, questo indica che ho incasinato la risposta o la navigazione nell'oggetto JSON. Lo apprezzerei se potessi sbirciare i pezzi di codice che ho cucito insieme dai tutorial sul web.Analisi JSON dell'API di Google Maps nell'app per Android

Questo codice ha lo scopo di ottenere la risposta. È circondato da un try/catch e non ha provocato alcun errore.

 String stringUrl = <URL GOES HERE>; 

     URL url = new URL(stringUrl); 
     HttpURLConnection httpconn = (HttpURLConnection)url.openConnection(); 
     if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) 
     { 
      BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192); 
      String strLine = null; 
      while ((strLine = input.readLine()) != null) 
      { 
       response.append(strLine); 
      } 
      input.close(); 
     } 
     String jsonOutput = response.toString(); 

Questo codice è destinato a tener che la produzione e analizzarlo nella stringa finale, durata, come ispirato this stackoverflow answer per una domanda simile.

 JSONObject jsonObject = new JSONObject(jsonOutput); 
     JSONObject routeObject = jsonObject.getJSONObject("routes"); 
     JSONObject legsObject = routeObject.getJSONObject("legs"); 
     JSONObject durationObject = legsObject.getJSONObject("duration"); 
     String duration = durationObject.getString("text"); 

Sto rilevando un'eccezione JSON sulla seconda riga del secondo blocco. Qualcuno può aiutare a risolvere questo problema? O forse suggerire un modo più semplice per ottenere gli stessi dati?

EDIT: grazie alla prima risposta utile qui (da aromero), della seconda metà ora assomiglia a:

JSONObject jsonObject = new JSONObject(responseText); 
    JSONArray routeObject = jsonObject.getJSONArray("routes"); 
    JSONArray legsObject = routeObject.getJSONArray(2); ***error*** 
    JSONObject durationObject = legsObject.getJSONObject(1); 
     String duration = durationObject.getString("text"); 

Ma è ancora gettando un'eccezione JSON, solo che ora è dopo la terza linea . Sono sicuro che questo sia imbarazzante facile da risolvere, ma apprezzerei davvero un po 'di aiuto.

La parte rilevante di un file JSON esempio è mostrato sotto:

{ 
    "routes" : [ 
     { 
     "bounds" : { 
      "northeast" : { 
       "lat" : 34.092810, 
       "lng" : -118.328860 
      }, 
      "southwest" : { 
       "lat" : 33.995590, 
       "lng" : -118.446040 
      } 
     }, 
     "copyrights" : "Map data ©2011 Google", 
     "legs" : [ 
      { 
       "distance" : { 
        "text" : "12.9 mi", 
        "value" : 20807 
       }, 
       "duration" : { 
        "text" : "27 mins", 
        "value" : 1619 
       }, 

risposta

14

"vie" è un array, invece di utilizzare getJSONObject, utilizzare getJSONArray

"gambe" è un array anche.

JSONObject jsonObject = new JSONObject(responseText); 

// routesArray contains ALL routes 
JSONArray routesArray = jsonObject.getJSONArray("routes"); 
// Grab the first route 
JSONObject route = routesArray.getJSONObject(0); 
// Take all legs from the route 
JSONArray legs = route.getJSONArray("legs"); 
// Grab first leg 
JSONObject leg = legs.getJSONObject(0); 

JSONObject durationObject = leg.getJSONObject("duration"); 
String duration = durationObject.getString("text"); 
+0

Credo che tu hai identificato quello che sto facendo male. Ancora stirare le specifiche. Lo posterò quando lo aggiusterò, a meno che qualcuno non mi picchi. – user714403

+0

I percorsi sono un array, presumo che Google ti stia restituendo un elenco di possibili percorsi. Quindi devi prenderne uno o fare qualcosa su tutti loro. Cosa stai cercando di fare? – aromero

+0

Fantastico! Grazie per la modifica alla tua risposta originale, apprezzo molto la tenuta della mano. Non ho davvero capito la sintassi/spaziatura del JSON e l'hai reso meravigliosamente chiaro. Grazie molto! – user714403

2

Stavo anche cercando di utilizzare la Direzione Api di Google in Android. Così ho creato un progetto open source per aiutare a farlo. Lo si può trovare qui: https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils

Come funziona, sicuramente semplicemente:

public class MainActivity extends ActionBarActivity implements DCACallBack{ 
/** 
* Get the Google Direction between mDevice location and the touched location using the  Walk 
* @param point 
*/ 
private void getDirections(LatLng point) { 
    GDirectionsApiUtils.getDirection(this, startPoint, endPoint, GDirectionsApiUtils.MODE_WALKING); 
} 

/* 
* The callback 
* When the directions is built from the google server and parsed, this method is called and give you the expected direction 
*/ 
@Override 
public void onDirectionLoaded(List<GDirection> directions) {   
    // Display the direction or use the DirectionsApiUtils 
    for(GDirection direction:directions) { 
     Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions); 
     GDirectionsApiUtils.drawGDirection(direction, mMap); 
    } 
} 
+0

È possibile per me implementare l'intero codice da Github alla mia app commerciale? –

Problemi correlati