【发布时间】:2014-12-15 09:42:25
【问题描述】:
我想检查在谷歌地图上绘制的新折线 A 是否与之前绘制的任何折线(B、C、D...)接触或重叠。在搜索解决方案期间,我得到了如下算法
Polyline findExistingPolyline(Polyline[] polylines, Polyline polyline) {
LatLng[] polylinePoints = PolylineDecoder.toLatLng(polyline);
for (Polyline existing: polylines) {
LatLng[] existingPoints = PolylineDecoder.toLatLng(existing);
if (isMostlyCovered(existingPoints , polylinePoints)) {
return existing;
}
}
return null;
}
boolean isMostlyCovered(LatLng[] existingPoints, LatLng[] polylinePoints) {
int initialSize = polylinePoints.length;
for (LatLng point: polylinePoints) {
for (LatLng existingPoint: existingPoints) {
if (distanceBetween(existingPoint, point) <= 100) {
polylinePoints.remove();// I actually use iterator, here it is just demosnstration
}
}
}
// check how many points are left and decide if polyline is mostly covered
// if 90% of the points is removed - existing polylines covers new polyline
return (polylinePoints.length * 100 / initialSize) <= 10;
}
在这个算法中,一个类 PolylineDecoder 将折线传递给它的方法,后来我在多个链接处发现了这个类,但几乎在每个地方它都接收到一个字符串而不是折线
public class PolylineDecoder {
public static ArrayList decodePoly(String encoded) {
ArrayList 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;
Location p = new Location((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
所以我将折线转换为字符串并将其传递给 PolylineDecoder 类
LatLng[] polylinePoints = PolylineDecoder.toLatLng(polyline.toString());
现在,当我运行程序时,它会在 PolylineDecoder 类中为第二个 do while 循环提供异常(字符串越界异常)
b = encoded.charAt(index++) - 63;
我该如何处理这个异常或者我错过了一些中间步骤?谢谢
【问题讨论】: