2016-07-07 203 views
0

我大致試圖從Google Distance Matrix API解析JSON,但它沒有顯示距離。谷歌距離矩陣沒有得到距離

我的GPS位置不是0,0,我確信。

String distance = getMatrix(latitude,longitude);

我的功能代碼爲:

private String getMatrix(double lat , double lang){ 
    JSONObject jObj; 
    String getdistance = ""; 
    String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" 
        + Double.toString(my_lat) + "," 
        + Double.toString(my_lang) 
        + "&destinations="+ Double.toString(lat) + "," 
        + Double.toString(lang) 
        + "&mode=walking&sensor=false"; 

    String data = ""; 
    InputStream reader = null; 
    HttpURLConnection urlConnection = null; 
    try{ 
    URL url = new URL(strUrl); 
    urlConnection = (HttpURLConnection) url.openConnection(); 
    urlConnection.connect(); 

    reader = urlConnection.getInputStream(); 
    int bRead = -1; 
    byte[] buffer = new byte[1024]; 
    do { 
     bRead = reader.read(buffer, 0, 1024); 
     if (bRead == -1) { 
     break; 
     } 
     data += new String(buffer, 0, bRead); 
    } while (true); 
    urlConnection.disconnect(); 
    } catch(Exception e) { 
    } finally { 

    } 

    try { 
    jObj = new JSONObject(data); 

    JSONArray rowsArray = jObj.getJSONArray("rows"); 
    JSONObject rows = rowsArray.getJSONObject(0); 

    JSONArray elementsArray = rows.getJSONArray("elements"); 
    JSONObject newDisTimeOb = elementsArray.getJSONObject(0); 

    JSONObject distOb = newDisTimeOb.getJSONObject("distance"); 
    getdistance = distOb.optString("text").toString(); 
    } catch (JSONException e) { 
    e.printStackTrace(); 
    } 

    return getdistance; 
} 

回答

0

首先,檢查你是否已經正確地構建代碼的URL字符串:

String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" 
        + Double.toString(my_lat) + "," 
        + Double.toString(my_lang) 
        + "&destinations="+ Double.toString(lat) + "," 
        + Double.toString(lang) 
        + "&mode=walking&sensor=false"; 

// Line to check if url code is right 
Log.d("APP", "strUrl = " + strUrl); 

然後檢查你的下面的代碼,不管是它真的產生的數據:

reader = urlConnection.getInputStream(); 
int bRead = -1; 
byte[] buffer = new byte[1024]; 
do { 
    bRead = reader.read(buffer, 0, 1024); 
    if (bRead == -1) { 
    break; 
    } 
    data += new String(buffer, 0, bRead); 
} while (true); 

我的建議離子是使用BufferedReader來讀取每個字節的響應字節。

然後改變:

getdistance = distOb.optString("text").toString(); 

getdistance = distOb.getString("text"); 

因爲你並不需要轉換爲字符串再次在這裏。

我搜索Client Libraries for Google Maps Web Services並找到DistanceMatrixApi.java。也許我們可以使用它,但我不能保證。