高度なコンセプト

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

データを取得しています

収集した位置情報データを取得する方法は数多くあります。ここでは、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 クライアントを使用して、場所 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 つは、多くの Google Maps Platform API で場所 ID を使用できることです。この例では、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 の住所のアノテーションが付けられています。

マーカーに表示される住所がジオコーディングされています

サンプルコード

考慮事項

この記事のコードは、説明用に 1 つの Android アプリとして提供されています。Android アプリではサーバーサイド API キーを配布しないでください。使用するキーは、サードパーティからの不正アクセスから保護できません。その代わりに、API 向けのコードをサーバー側プロキシとしてデプロイし、Android アプリがプロキシ経由でリクエストを送信して、リクエストが確実に認可されるようにする必要があります。

ダウンロード

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