高度なコンセプト

データを取得しています

収集した位置情報データを取得する方法は多数あります。ここでは、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 位置情報のサンプルをご覧ください。

長いパスを処理しています

道路へのスナップ機能は、個々の地点ではなく完全な経路に基づいて位置を推測するため、長い経路(リクエストあたり 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 クライアントを使用して、上記のスナップ地点の道路リクエストから返された場所をジオコーディングします。

/**
 * 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;
}

ここでは、制限 API に Geocoding API のアドレスのアノテーションが付けられています。

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

サンプルコード

考慮事項

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

ダウンロード

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