高级概念

获取数据

有多种方法可以获取收集到的位置数据。在这里,我们将介绍 用于获取数据的技巧,这些数据将与道路快照功能搭配使用 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 培训课程 更新以及 Google Play 位置示例 GitHub

处理长路径

由于道路紧贴功能会根据完整路径推断位置, 处理长篇内容 路径(即超过 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;
}

以下是运行道路吸附请求后由以上生成的数据。红色的 线是原始数据,蓝线是吸附数据。

已贴靠道路的数据示例

配额高效利用

snap to Roads 请求的响应包含地点 ID 列表 这些点与您提供的点对应,如果您 设置interpolate=true

为了高效利用您针对速度限制请求允许的配额, 您只应在请求中查询唯一的地点 ID。本示例使用 适用于 Google 地图服务的 Java 客户端,用于从地点列表查询速度限制 。

/**
 * 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 Maps Platform 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 应用 仅作说明之用。在实践中,您不应将服务器端 API 密钥,因为无法保护密钥免遭未经授权的访问 通过第三方访问。相反,为了保障密钥的安全,您应该将 作为服务器端代理的面向 API 的代码,让您的 Android 应用发送请求 确保请求获得授权

下载

GitHub 下载代码。