【问题标题】:Decoding a polyline in android在android中解码折线
【发布时间】: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;

我该如何处理这个异常或者我错过了一些中间步骤?谢谢

【问题讨论】:

    标签: android polyline


    【解决方案1】:

    我们应该对 String 折线中的任何 Java 文字进行转义。可以使用

    StringEscapeUtils.unescapeJava(polyline)
    

    上面可以改成

    polyline  = StringEscapeUtils.unescapeJava(polyline.toString());
    LatLng[] polylinePoints = PolylineDecoder.toLatLng(polyline);
    

    【讨论】:

      猜你喜欢
      • 2012-02-11
      • 2017-02-12
      • 2020-08-12
      • 2021-03-23
      • 2012-03-04
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多