高度なコンセプト

データの取得

収集された位置情報は、さまざまな方法で取得できます。ここでは、Roads API道路へのスナップ機能で使用するデータを取得する 2 つの方法について説明します。

GPX

GPX は、GPS デバイスでキャプチャされたルート、トラック、ウェイポイントを共有するためのオープンな XML ベースの形式です。この例では、Java サーバーとモバイル環境の両方で使用できる軽量の XML パーサーである XmlPull パーサーを使用します。

/**
 * 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 Location サンプルをご覧ください。

長いパスの処理

「道路へのスナップ」機能は、個々の地点ではなく、フルパスに基づいて場所を推測するため、長いパス(リクエストごとに 100 ポイントの上限を超えるパス)を処理する場合は注意が必要です。

個々のリクエストを 1 つの長いパスとして扱うには、前のリクエストの最後のポイントが後続のリクエストの最初のポイントに含まれるように、一部を重複させる必要があります。追加するポイントの数は、データの精度によって異なります。リクエストの精度が低い場合は、より多くのポイントを含める必要があります。

この例では、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 Client を使用して、プレイス 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 が返されるメリットの 1 つは、プレイス ID を多くの Google Maps Platform API で使用できることです。このサンプルでは、Google マップ サービス向け Java Client を使用して、上記の道路へのスナップのリクエストから返された場所をジオコーディングしています。

/**
 * 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 に対応するコードをサーバーサイド プロキシとしてデプロイし、Android アプリがこのプロキシ経由でリクエストを送信することで、キーを保護するには、リクエストが承認されるようにする必要があります。

ダウンロード

GitHub からコードをダウンロードします。