正在取得資料
取得位置資料的方法有很多種。我們說明兩種取得資料的技術,或者是搭配 Roads API 的「傳送道路資料」功能使用資料。
GPX
GPX 是一種開放的 XML 格式,可分享 GPS 裝置擷取的路線、歷程和路線控點。本範例使用 XmlPull 剖析器,這是適用於 Java 伺服器和行動裝置環境的輕量 XML 剖析器。
/** * Parses the waypoint (wpt tags) data into native objects from a GPX stream. */ private List<LatLng> loadGpxData(XmlPullParser parser, InputStream gpxIn) throws XmlPullParserException, IOException { // We use a List<> as we need subList for paging later List<LatLng> latLngs = new ArrayList<>(); parser.setInput(gpxIn, null); parser.nextTag(); while (parser.next() != XmlPullParser.END_DOCUMENT) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } if (parser.getName().equals("wpt")) { // Save the discovered latitude/longitude attributes in each <wpt>. latLngs.add(new LatLng( Double.valueOf(parser.getAttributeValue(null, "lat")), Double.valueOf(parser.getAttributeValue(null, "lon")))); } // Otherwise, skip irrelevant data } return latLngs; }
以下是一些已載入在地圖上的原始 GPX 資料。
Android 定位服務
從 Android 裝置擷取 GPS 資料的最佳方式會因用途而異。請前往「接收位置更新」瞭解 Android 訓練課程,以及 GitHub 上的 Google Play 位置範例。
正在處理長路徑
由於「道路救援」功能會根據完整路徑 (而非個別點) 推斷位置,因此處理較長的路徑時 (也就是路徑超過每個要求的 100 個資料點限制)。
如要將個別要求視為一長路徑,您應加入一些重疊部分,以將先前要求的最終資料點納入為後續要求的第一個點。要納入的資料點數目取決於資料的準確性。您應針對低精確度的要求加入更多資料點。
本例使用 Google 地圖服務適用的 Java 用戶端傳送分頁要求,然後將資料 (包括內插點) 重新加入傳回的清單。
/** * Snaps the points to their most likely position on roads using the Roads API. */ private List<SnappedPoint> snapToRoads(GeoApiContext context) throws Exception { List<SnappedPoint> snappedPoints = new ArrayList<>(); int offset = 0; while (offset < mCapturedLocations.size()) { // Calculate which points to include in this request. We can't exceed the API's // maximum and we want to ensure some overlap so the API can infer a good location for // the first few points in each request. if (offset > 0) { offset -= PAGINATION_OVERLAP; // Rewind to include some previous points. } int lowerBound = offset; int upperBound = Math.min(offset + PAGE_SIZE_LIMIT, mCapturedLocations.size()); // Get the data we need for this page. LatLng[] page = mCapturedLocations .subList(lowerBound, upperBound) .toArray(new LatLng[upperBound - lowerBound]); // Perform the request. Because we have interpolate=true, we will get extra data points // between our originally requested path. To ensure we can concatenate these points, we // only start adding once we've hit the first new point (that is, skip the overlap). SnappedPoint[] points = RoadsApi.snapToRoads(context, true, page).await(); boolean passedOverlap = false; for (SnappedPoint point : points) { if (offset == 0 || point.originalIndex >= PAGINATION_OVERLAP - 1) { passedOverlap = true; } if (passedOverlap) { snappedPoints.add(point); } } offset = upperBound; } return snappedPoints; }
以下是對道路提出比對要求之後的資料。紅線是原始資料,藍線則是已接合的資料。
有效率地使用配額
「道路救援」要求的回應中會包含一份與所提供地點對應的地點 ID 清單,如果您設定 interpolate=true
,可能還會包含其他地點。
為有效運用允許的配額用於速限要求,建議您只在要求中查詢不重複的地點 ID。此範例使用 Google 地圖服務適用的 Java 用戶端,查詢地點 ID 清單中的速限。
/** * Retrieves speed limits for the previously-snapped points. This method is efficient in terms * of quota usage as it will only query for unique places. * * Note: Speed limit data is only available for requests using an API key enabled for a * Google Maps APIs Premium Plan license. */ private Map<String, SpeedLimit> getSpeedLimits(GeoApiContext context, List<SnappedPoint> points) throws Exception { Map<String, SpeedLimit> placeSpeeds = new HashMap<>(); // Pro tip: Save on quota by filtering to unique place IDs. for (SnappedPoint point : points) { placeSpeeds.put(point.placeId, null); } String[] uniquePlaceIds = placeSpeeds.keySet().toArray(new String[placeSpeeds.keySet().size()]); // Loop through the places, one page (API request) at a time. for (int i = 0; i < uniquePlaceIds.length; i += PAGE_SIZE_LIMIT) { String[] page = Arrays.copyOfRange(uniquePlaceIds, i, Math.min(i + PAGE_SIZE_LIMIT, uniquePlaceIds.length)); // Execute! SpeedLimit[] placeLimits = RoadsApi.speedLimits(context, page).await(); for (SpeedLimit sl : placeLimits) { placeSpeeds.put(sl.placeId, sl); } } return placeSpeeds; }
以上資料,其中包含各專屬地點 ID 的速限標示。
與其他 API 互動
在前往道路的空印回應中傳回地點 ID 的其中一項好處,就是可以在許多 Google 地圖平台 API 中使用地點 ID。此範例使用 Google 地圖服務適用的 Java 用戶端,為上述傳回的地點進行地理編碼到道路要求。
/** * Geocodes a snapped point using the place ID. */ private GeocodingResult geocodeSnappedPoint(GeoApiContext context, SnappedPoint point) throws Exception { GeocodingResult[] results = GeocodingApi.newRequest(context) .place(point.placeId) .await(); if (results.length > 0) { return results[0]; } return null; }
這裡的速限標記已經使用 Geocoding API 中的地址加註。
程式碼範例
注意事項
為進行說明,本文支援的程式碼可做為單一 Android 應用程式使用。實際上,您不應在 Android 應用程式中發布伺服器端 API 金鑰,因為金鑰無法防止第三方在未經授權的情況下存取。為了保護金鑰,您應將 API 端的程式碼部署為伺服器端 Proxy,並讓您的 Android 應用程式透過 Proxy 傳送要求,確保要求已獲得授權。
下載
從 GitHub 下載程式碼。