進階概念

正在取得資料

取得所蒐集位置資料的方法有很多種。我們將說明兩種取得資料,以便與 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 資料。

地圖上的原始 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 應用程式的形式提供。實務上,您不應將伺服器端 API 金鑰發布到 Android 應用程式中,因為金鑰無法防止第三方在未經授權的情況下擅自存取。因此,為保護金鑰安全,您應將面向 API 的程式碼部署為伺服器端 Proxy,並讓 Android 應用程式透過 Proxy 傳送要求,確保要求已獲得授權。

下載

GitHub 下載程式碼。