2012-02-12 58 views
1

我有一個應用程序,在給google地圖的url請求中給出2個postcode後分析一個json響應。我從響應中獲得了overviewpolyline節點並將其轉換爲字符串。我認爲overviewpolyline節點是作爲折線的整個路線。給我StringIndexOutOfBoundsException的多義線解碼器

下面是一些代碼,我發現當將多段線​​作爲字符串傳遞時,它將該字符串轉換爲GeoPoints列表。我已經檢查過折線字符串是否爲空,例如2個郵編中有700多個字符。所以沒有問題。

我已經在下面的代碼源中標記了發生異常的位置。任何想法爲什麼有索引錯誤。循環由'while'語句控制,並且只在少於多段線長度時迭代。

@SuppressWarnings("unchecked") 
    private List decodePolyLine(final String poly) { 



     int len = poly.length(); 
     Log.e(TAG, "poly string length = "+poly.length()); 
     int index = 0; 
     List decoded = new ArrayList(); 
     int lat = 0; 
     int lng = 0; 


     while (index < len) { 

     int b; 
     int shift = 0; 
     int result = 0; 

     do { 

     b = poly.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 = poly.charAt(index++) - 63;  <--------****error here**** 
     result |= (b & 0x1f) << shift; 
     shift += 5; 

     } while (b >= 0x20); 



     int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 
     lng += dlng; 

     decoded.add(new GeoPoint(

       (int)(lat*1e6) , (int)(lon * 1e6))); 

     } 

     return decoded; 

     }//end of decodePolyLine 
+0

我剛剛注意到overviewpolyline有一個嵌套的對象「點」。現在就看看那個。 – turtleboy 2012-02-12 11:40:54

回答

0

解決了。問題不在於上面的代碼,而是我如何解析json響應。我需要獲取overviewpolyline對象中的點對象。例如

JSONObject results = null; 

     try { 

      results = new JSONObject(jsonOutput); 


      routes = results.getJSONArray("routes"); 

      anonObject = routes.getJSONObject(0); 
      bounds = anonObject.getJSONObject("bounds"); 
      overViewPolyline = anonObject.getJSONObject("overview_polyline"); 
      polyPoints = overViewPolyline.getString("points"); 
      Log.e(TAG,"overview_polyline = " + overViewPolyline); 
      Log.e(TAG,"points = " + polyPoints); 


      northeast = bounds.getJSONObject("northeast"); 


      lat = (Double) northeast.get("lat"); 


      lon = (Double) northeast.get("lng"); 


     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }