请求返回的数据样式,由于我的Android studio展示的Log日志过短,无法显示完全结果,所以我将完全结果图片展示出来,方便大家查看结果
当使用这个方法的时候遇到跨江的桥的时候,会偏离桥直接跨江过去。这里需要改正的是解析结果,不解析steps而解析overview_polyline对象中有一个points是路线的集合,这里只是猜测有可能是数据太多所以才以这种方式返回的,这个只是猜想。
修改之后的代码:
/****
* 路线经纬度
* @param start
* @param end
* @param httpCallBack
*/
public static void distanceMatrix(final boolean isShow, final LatLng start, LatLng end, final HttpCallBack httpCallBack) {
/*请求地址*/
String url = "https://maps.googleapis.com/maps/api/directions/json?";
/*相关参数*/
String params = "origin=" + start.latitude + "," + start.longitude +
"&destination=" + end.latitude + "," + end.longitude + "&mode=driving&sensor=false"
+ "&language=zh-CN&key=" + Constant.GOOGLE_MAP;
Request request = new Request.Builder()
.url(url + params).get().build();
if (isShow)
Http.getInstance().show();
httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (isShow)
Http.getInstance().dismiss();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
String result = response.body().string();
Log.e("qza", result);
try {
JSONObject object = new JSONObject(result);
RouteEntity routeEntity = new RouteEntity();
JSONArray routes = object.optJSONArray("routes");
if (routes.length() == 0) {
return;
}
JSONObject data = routes.optJSONObject(0);
JSONArray legs = data.optJSONArray("legs");
routeEntity.distance = legs.optJSONObject(0)
.optJSONObject("distance").optString("text");
routeEntity.duration = legs.optJSONObject(0)
.optJSONObject("duration").optString("text");
JSONObject polyline = data.optJSONObject("overview_polyline");
String points = polyline.optString("points");
routeEntity.lngList.addAll(decodePoly(points)) ;
if (httpCallBack != null)
httpCallBack.onSuccess(routeEntity);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (httpCallBack != null)
onFail(response.code(), httpCallBack);
}
}
});
}
/**
* 解析返回xml中overview_polyline的路线编码
*
* @param encoded
* @return List
*/
private static List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
希望可以帮助到你,这里只是作为遇到问题的记载。