我大致试图从comment解析JSON,但它没有显示距离。
我的GPS位置不是我确定的0,0
。
String distance = getMatrix(纬度,经度);
我的功能代码是:
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 :(得分: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。也许我们可以使用它,但我不能保证它。