大家好。我有一个关于绘制谷歌地图路线(步行、驾车、公交)的问题..
所以:我调用一个 url ex: 字符串 urlToCall = "http://maps.googleapis.com/maps/api/directions/json " + "?origin="+getMyLat() + ","+ getMyLong() + "&destination="+ Double.parseDouble(eventLocationLat) + ","+ Double.parseDouble(eventLocationLong) +“&传感器=真” + "&language="+ Locale.getDefault().getLanguage() + "&departure_time="+ System.currentTimeMillis()/1000 + "&mode="+ getMovingMode();
一切都很好,并返回一个 JSON。从这里开始,我的下一步是画一条上线,显示整个路线,所以:
private void drawRouteOnMap(String httpResult) {
JSONObject routeObject = null;
try {
routeObject = new JSONObject(httpResult).optJSONArray("routes").optJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String polyLine = null;
try {
polyLine = routeObject.optJSONObject("overview_polyline").getString("points");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(polyLine != null){
// Log.e("polyLine", polyLine);
setDecodedPoly( GoogleMapsCustomHelpers.decodePoly( polyLine ) );
}
setUpMapIfNeeded();
}
到这里为止一切都很好,但它在“decodePoly”方法中给出了“IndexOutOfBoundsException”。 我评论了女巫抛出异常这一行:
公共(public)静态列表decodePoly(字符串编码){
List<LatLng> poly = new ArrayList<LatLng>();
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; // ERROR: INDEX OUT OF BOUND
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;
}
所以,我的问题是:出了什么问题?我没有从谷歌地图中找到任何类来处理PolyLine解码,什么都没有..我不知道出了什么问题。使用在线解码器进行测试(基于V3,我认为所有折线在 map 上都绘制正常,但在我的代码中它们崩溃了..)
我发现的唯一区别是在我的代码中:
//efovGyqkrCvBxDu@jAmAzAhAnBPEPBTTf@f@rCvCeAtBo@fB@NdCbClDeFfCqD@q@w@mAk@oA[yA?g@BOJYl@w@n@q@WD?JAn@dAP
@^e@
它崩溃了,但是当我在“https://developers.google.com/maps/documentation/utilities/polylineutility”中测试它时,它被正确绘制,并且它在编码的折线中添加了一个“@”。在其他情况下,它添加了“s@”
谁能告诉我我做错了什么?提前致谢!
最佳答案
我成功解决了这个问题。我们应该对 String poly 行中找到的任何 Java 文字进行转义。可以使用 StringEscapeUtils.unescapeJava(polyLine)
来完成
上面可以改成
if(polyLine != null){
// Log.e("polyLine", polyLine);
polyLine = StringEscapeUtils.unescapeJava(polyLine);
setDecodedPoly( GoogleMapsCustomHelpers.decodePoly( polyLine ) );
}
关于Android Google Maps Api V2 PolyLine 解码索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20493405/