android在google map上畫線比較容易實現的,但是現在問題在於如何擷取起點和終點之間的路線圖。這裡我們使用Google Directions API來實現, Google Directions API是一種使用 HTTP 請求計算多個位置間路線的服務。路線可以以文本字串或緯度/經度座標的形式指定起點、目的地和路標。Google Directions API 可以使用一系列路標傳回多段路線。
Google Directions API 請求是以下形式的 HTTP 網址:http://maps.google.com/maps/api/directions/output?parameters
其中,output 可能是以下任何一個值:
l json(建議)表示以 JavaScript 對象標記法 (JSON) 的形式輸出
l xml 表示以 XML 的形式輸出
具體參數參見http://code.google.com/intl/zh-CN/apis/maps/documentation/directions/
通過http請求擷取線路,接下來我們需要對返回結果進行解析,提取出導航線路的一系列路標。
如果我們只是簡單的畫圖路線路,返回結果中的欄位overview_path包含可我們所需要的資料。它包含一個對象,該對象包含一組表示產生路線的近似(平滑)路徑的已編碼 points 和 levels。編碼演算法參見http://code.google.com/intl/zh-CN/apis/maps/documentation/utilities/polylinealgorithm.html說明。
我們只需要提取points欄位中的字串進行解碼就可以得到我們所需的一系列點了,將這些點按順序串連起來就是我們所要的路線圖了。
/** * 通過解析google map返回的xml,在map中畫路線圖 */public void drawRoute(){String url = "http://maps.google.com/maps/api/directions/xml?origin=23.055291,113.391802" +"&destination=23.046604,113.397510&sensor=false&mode=walking";HttpGet get = new HttpGet(url);String strResult = "";try {HttpParams httpParameters = new BasicHttpParams();HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse httpResponse = null;httpResponse = httpClient.execute(get);if (httpResponse.getStatusLine().getStatusCode() == 200){strResult = EntityUtils.toString(httpResponse.getEntity());}} catch (Exception e) {return;}if (-1 == strResult.indexOf("<status>OK</status>")){Toast.makeText(this, "擷取導航路線失敗!", Toast.LENGTH_SHORT).show();this.finish();return;}int pos = strResult.indexOf("<overview_polyline>");pos = strResult.indexOf("<points>", pos + 1);int pos2 = strResult.indexOf("</points>", pos);strResult = strResult.substring(pos + 8, pos2);List<GeoPoint> points = decodePoly(strResult);MyOverLay mOverlay = new MyOverLay(points);List<Overlay> overlays = mMapView.getOverlays();overlays.add(mOverlay);if (points.size() >= 2){mMapController.animateTo(points.get(0));} mMapView.invalidate();} /** * 解析返回xml中overview_polyline的路線編碼 * * @param encoded * @return */private List<GeoPoint> decodePoly(String encoded) { List<GeoPoint> poly = new ArrayList<GeoPoint>(); 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; GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6), (int) (((double) lng / 1E5) * 1E6)); poly.add(p); } return poly;}
本文來源