2016-07-07 139 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。也许我们可以使用它,但我不能保证。