進階概念

取得資料

有很多方法可以取得收集到的位置資料。以下說明兩種取得資料以與 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 的好處之一,就是您可以將地點 ID 用於許多 Google 地圖平台 API。本例使用 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 下載程式碼。