単一目的地のルートをナビゲートする

このガイドでは、Navigation SDK for Android を使用してアプリ内でルートを作成する方法について説明します。このガイドでは、プロジェクトを設定するで説明されているように、Navigation SDK をアプリにすでに統合していることを前提としています。

概要

  1. ナビゲーション フラグメントまたはナビゲーション ビューとして、UI 要素をアプリに追加します。この UI 要素は、インタラクティブな地図とターンバイターン ナビゲーション UI をアクティビティに追加します。
  2. 位置情報の利用許可をリクエストします。アプリは、デバイスの位置情報を特定するために位置情報の利用許可をリクエストする必要があります。
  3. NavigationApi クラスを使用して SDK を初期化します。
  4. Navigator クラスを使用して、目的地を設定し、ターンバイターン ナビゲーションを制御します。このプロセスには次の 3 つのステップがあります。

    • setDestination() を使用して宛先を設定します。
    • startGuidance() でナビを開始します。
    • getSimulator() を使用して、ルート上の車両の進行状況をシミュレートし、アプリのテスト、デバッグ、デモを行います。
  5. アプリをビルドして実行します。

コードの確認

package com.example.navsdksingledestination;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.maps.GoogleMap.CameraPerspective;
import com.google.android.libraries.navigation.ListenableResultFuture;
import com.google.android.libraries.navigation.NavigationApi;
import com.google.android.libraries.navigation.Navigator;
import com.google.android.libraries.navigation.RoutingOptions;
import com.google.android.libraries.navigation.SimulationOptions;
import com.google.android.libraries.navigation.SupportNavigationFragment;
import com.google.android.libraries.navigation.Waypoint;

/**
 * An activity that displays a map and a navigation UI, guiding the user from their current location
 * to a single, given destination.
 */
public class NavigationActivitySingleDestination extends AppCompatActivity {

  private static final String TAG = NavigationActivitySingleDestination.class.getSimpleName();
  private Navigator mNavigator;
  private SupportNavigationFragment mNavFragment;
  private RoutingOptions mRoutingOptions;

  // Define the Sydney Opera House by specifying its place ID.
  private static final String SYDNEY_OPERA_HOUSE = "ChIJ3S-JXmauEmsRUcIaWtf4MzE";

  // Set fields for requesting location permission.
  private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
  private boolean mLocationPermissionGranted;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initialize the Navigation SDK.
    initializeNavigationSdk();
  }

  /**
   * Starts the Navigation SDK and sets the camera to follow the device's location. Calls the
   * navigateToPlace() method when the navigator is ready.
   */
  private void initializeNavigationSdk() {
    /*
     * Request location permission, so that we can get the location of the
     * device. The result of the permission request is handled by a callback,
     * onRequestPermissionsResult.
     */
    if (ContextCompat.checkSelfPermission(
            this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION)
        == PackageManager.PERMISSION_GRANTED) {
      mLocationPermissionGranted = true;
    } else {
      ActivityCompat.requestPermissions(
          this,
          new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION},
          PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }

    if (!mLocationPermissionGranted) {
      displayMessage(
          "Error loading Navigation SDK: " + "The user has not granted location permission.");
      return;
    }

    // Get a navigator.
    NavigationApi.getNavigator(
        this,
        new NavigationApi.NavigatorListener() {
          /** Sets up the navigation UI when the navigator is ready for use. */
          @Override
          public void onNavigatorReady(Navigator navigator) {
            displayMessage("Navigator ready.");
            mNavigator = navigator;
            mNavFragment =
                (SupportNavigationFragment)
                    getSupportFragmentManager().findFragmentById(R.id.navigation_fragment);

            // Set the last digit of the car's license plate to get route restrictions
            // in supported countries. (optional)
            // mNavigator.setLicensePlateRestrictionInfo(getLastDigit(), "BZ");

            // Set the camera to follow the device location with 'TILTED' driving view.
            mNavFragment.getMapAsync(
                googleMap -> googleMap.followMyLocation(CameraPerspective.TILTED));

            // Set the travel mode (DRIVING, WALKING, CYCLING, or TWO_WHEELER).
            mRoutingOptions = new RoutingOptions();
            mRoutingOptions.travelMode(RoutingOptions.TravelMode.DRIVING);

            // Navigate to a place, specified by Place ID.
            navigateToPlace(SYDNEY_OPERA_HOUSE, mRoutingOptions);
          }

          /**
           * Handles errors from the Navigation SDK.
           *
           * @param errorCode The error code returned by the navigator.
           */
          @Override
          public void onError(@NavigationApi.ErrorCode int errorCode) {
            switch (errorCode) {
              case NavigationApi.ErrorCode.NOT_AUTHORIZED:
                displayMessage(
                    "Error loading Navigation SDK: Your API key is "
                        + "invalid or not authorized to use the Navigation SDK.");
                break;
              case NavigationApi.ErrorCode.TERMS_NOT_ACCEPTED:
                displayMessage(
                    "Error loading Navigation SDK: User did not accept "
                        + "the Navigation Terms of Use.");
                break;
              case NavigationApi.ErrorCode.NETWORK_ERROR:
                displayMessage("Error loading Navigation SDK: Network error.");
                break;
              case NavigationApi.ErrorCode.LOCATION_PERMISSION_MISSING:
                displayMessage(
                    "Error loading Navigation SDK: Location permission " + "is missing.");
                break;
              default:
                displayMessage("Error loading Navigation SDK: " + errorCode);
            }
          }
        });
  }

  /**
   * Requests directions from the user's current location to a specific place (provided by the
   * Google Places API).
   */
  private void navigateToPlace(String placeId, RoutingOptions travelMode) {
    Waypoint destination;
    try {
      destination = Waypoint.builder().setPlaceIdString(placeId).build();
    } catch (Waypoint.UnsupportedPlaceIdException e) {
      displayMessage("Error starting navigation: Place ID is not supported.");
      return;
    }

    // Create a future to await the result of the asynchronous navigator task.
    ListenableResultFuture<Navigator.RouteStatus> pendingRoute =
        mNavigator.setDestination(destination, travelMode);

    // Define the action to perform when the SDK has determined the route.
    pendingRoute.setOnResultListener(
        new ListenableResultFuture.OnResultListener<Navigator.RouteStatus>() {
          @Override
          public void onResult(Navigator.RouteStatus code) {
            switch (code) {
              case OK:
                // Hide the toolbar to maximize the navigation UI.
                if (getActionBar() != null) {
                  getActionBar().hide();
                }

                // Enable voice audio guidance (through the device speaker).
                mNavigator.setAudioGuidance(Navigator.AudioGuidance.VOICE_ALERTS_AND_GUIDANCE);

                // Simulate vehicle progress along the route for demo/debug builds.
                if (BuildConfig.DEBUG) {
                  mNavigator
                      .getSimulator()
                      .simulateLocationsAlongExistingRoute(
                          new SimulationOptions().speedMultiplier(5));
                }

                // Start turn-by-turn guidance along the current route.
                mNavigator.startGuidance();
                break;
              // Handle error conditions returned by the navigator.
              case NO_ROUTE_FOUND:
                displayMessage("Error starting navigation: No route found.");
                break;
              case NETWORK_ERROR:
                displayMessage("Error starting navigation: Network error.");
                break;
              case ROUTE_CANCELED:
                displayMessage("Error starting navigation: Route canceled.");
                break;
              default:
                displayMessage("Error starting navigation: " + String.valueOf(code));
            }
          }
        });
  }

  /** Handles the result of the request for location permissions. */
  @Override
  public void onRequestPermissionsResult(
      int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    mLocationPermissionGranted = false;
    switch (requestCode) {
      case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:
        {
          // If request is canceled, the result arrays are empty.
          if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mLocationPermissionGranted = true;
          }
        }
    }
  }

  /**
   * Shows a message on screen and in the log. Used when something goes wrong.
   *
   * @param errorMessage The message to display.
   */
  private void displayMessage(String errorMessage) {
    Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
    Log.d(TAG, errorMessage);
  }
}

アプリに UI 要素を追加する

このセクションでは、ターンバイターン ナビゲーションを表示するインタラクティブな地図と UI を追加する 2 つの方法について説明します。ほとんどの場合、NavigationView を直接操作するのではなく、NavigationView のラッパーである SupportNavigationFragment を使用することをおすすめします。詳しくは、ナビゲーション マップの操作に関するベスト プラクティス をご覧ください。

SupportNavigationFragment は、インタラクティブな地図やルート案内など、ナビゲーションの視覚的な出力を表示する UI コンポーネントです。フラグメントは、次のように XML レイアウト ファイルで宣言できます。

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:name="com.google.android.libraries.navigation.SupportNavigationFragment"
    android:id="@+id/navigation_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

または、Android のドキュメントに記載されているように、FragmentActivity.getSupportFragmentManager() を使用してフラグメントをプログラムで作成することもできます。

フラグメントの代わりに、ナビゲーション用の地図を表示する UI コンポーネントを NavigationView として使用することもできます。

位置情報の利用許可をリクエストする

このセクションでは、正確な位置情報の権限をリクエストする方法について説明します。詳細については、Android の権限に関するガイドをご覧ください。

  1. Android マニフェストの <manifest> 要素の子として権限を追加します。

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.navsdksingledestination">
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    </manifest>
    
  2. アプリで実行時の権限をリクエストし、ユーザーに位置情報の利用許可を付与または拒否する機会を提供します。次のコードは、ユーザーが正確な位置情報の権限を付与しているかどうかを確認します。許可していない場合は、パーミッションをリクエストします。

    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    } else {
        ActivityCompat.requestPermissions(this,
                new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION },
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }
    
    if (!mLocationPermissionGranted) {
        displayMessage("Error loading Navigation SDK: "
                + "The user has not granted location permission.");
        return;
    }
    
  3. onRequestPermissionsResult() コールバックをオーバーライドして、権限リクエストの結果を処理します。

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is canceled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
    }
    

Navigation SDK を初期化する

NavigationApi クラスは、Google ナビゲーションの使用をアプリに許可する初期化ロジックを提供します。このセクションでは、ナビゲータを初期化する方法と、アプリで有効にできるその他の構成について説明します。

  1. Navigation SDK を初期化し、onNavigatorReady() コールバックをオーバーライドして、ナビゲータの準備が整ったらナビゲーションを開始します。

  2. 省略可。ユーザーがデバイスからアプリを閉じると、ガイダンス通知とバックグラウンド サービスがシャットダウンされるようにアプリを構成します。この選択は、ビジネスモデルによって異なります。デフォルトのナビゲータの動作を使用すると、アプリが閉じられても、曲がり角の案内と位置情報の更新が引き続き表示されます。エンドユーザーがアプリを閉じたときにナビゲーションと位置情報の更新を停止する場合は、この構成を使用します。

  3. 省略可。サポートされている国で道路規制を有効にします。ナンバープレートの末尾の数字を設定します。この呼び出しは 1 回だけ行う必要があります。その後のルート検索リクエストでも引き続き使用されます。この呼び出しは、サポートされているリージョンでのみ機能します。Navigation SDK でサポートされている国をご覧ください。

    NavigationApi.getNavigator(this, new NavigationApi.NavigatorListener() {
                /**
                 * Sets up the navigation UI when the navigator is ready for use.
                 */
                @Override
                public void onNavigatorReady(Navigator navigator) {
                    displayMessage("Navigator ready.");
                    mNavigator = navigator;
                    mNavFragment = (NavigationFragment) getFragmentManager()
                            .findFragmentById(R.id.navigation_fragment);
    
                    // Optional. Disable the guidance notifications and shut down the app
                    // and background service when the user closes the app.
                    // mNavigator.setTaskRemovedBehavior(Navigator.TaskRemovedBehavior.QUIT_SERVICE)
    
                    // Optional. Set the last digit of the car's license plate to get
                    // route restrictions for supported countries.
                    // mNavigator.setLicensePlateRestrictionInfo(getLastDigit(), "BZ");
    
                    // Set the camera to follow the device location with 'TILTED' driving view.
                    mNavFragment.getCamera().followMyLocation(Camera.Perspective.TILTED);
    
                    // Set the travel mode (DRIVING, WALKING, CYCLING, TWO_WHEELER, or TAXI).
                    mRoutingOptions = new RoutingOptions();
                    mRoutingOptions.travelMode(RoutingOptions.TravelMode.DRIVING);
    
                    // Navigate to a place, specified by Place ID.
                    navigateToPlace(SYDNEY_OPERA_HOUSE, mRoutingOptions);
                }
    
                /**
                 * Handles errors from the Navigation SDK.
                 * @param errorCode The error code returned by the navigator.
                 */
                @Override
                public void onError(@NavigationApi.ErrorCode int errorCode) {
                    switch (errorCode) {
                        case NavigationApi.ErrorCode.NOT_AUTHORIZED:
                            displayMessage("Error loading Navigation SDK: Your API key is "
                                    + "invalid or not authorized to use the Navigation SDK.");
                            break;
                        case NavigationApi.ErrorCode.TERMS_NOT_ACCEPTED:
                            displayMessage("Error loading Navigation SDK: User did not accept "
                                    + "the Navigation Terms of Use.");
                            break;
                        case NavigationApi.ErrorCode.NETWORK_ERROR:
                            displayMessage("Error loading Navigation SDK: Network error.");
                            break;
                        case NavigationApi.ErrorCode.LOCATION_PERMISSION_MISSING:
                            displayMessage("Error loading Navigation SDK: Location permission "
                                    + "is missing.");
                            break;
                        default:
                            displayMessage("Error loading Navigation SDK: " + errorCode);
                    }
                }
            });
    

宛先を設定する

Navigator クラスは、ナビゲーション ジャーニーの構成、開始、停止を制御します。

前のセクションで取得した Navigator を使用して、このルートの目的地 Waypoint を設定します。ルートの計算が完了すると、SupportNavigationFragment に、地図上にルートを表すポリラインと、目的地のマーカーが表示されます。

    private void navigateToPlace(String placeId, RoutingOptions travelMode) {
        Waypoint destination;
        try {
            destination = Waypoint.builder().setPlaceIdString(placeId).build();
        } catch (Waypoint.UnsupportedPlaceIdException e) {
            displayMessage("Error starting navigation: Place ID is not supported.");
            return;
        }

        // Create a future to await the result of the asynchronous navigator task.
        ListenableResultFuture<Navigator.RouteStatus> pendingRoute =
                mNavigator.setDestination(destination, travelMode);

        // Define the action to perform when the SDK has determined the route.
        pendingRoute.setOnResultListener(
                new ListenableResultFuture.OnResultListener<Navigator.RouteStatus>() {
                    @Override
                    public void onResult(Navigator.RouteStatus code) {
                        switch (code) {
                            case OK:
                                // Hide the toolbar to maximize the navigation UI.
                                if (getActionBar() != null) {
                                    getActionBar().hide();
                                }

                                // Enable voice audio guidance (through the device speaker).
                                mNavigator.setAudioGuidance(
                                        Navigator.AudioGuidance.VOICE_ALERTS_AND_GUIDANCE);

                                // Simulate vehicle progress along the route for demo/debug builds.
                                if (BuildConfig.DEBUG) {
                                    mNavigator.getSimulator().simulateLocationsAlongExistingRoute(
                                            new SimulationOptions().speedMultiplier(5));
                                }

                                // Start turn-by-turn guidance along the current route.
                                mNavigator.startGuidance();
                                break;
                            // Handle error conditions returned by the navigator.
                            case NO_ROUTE_FOUND:
                                displayMessage("Error starting navigation: No route found.");
                                break;
                            case NETWORK_ERROR:
                                displayMessage("Error starting navigation: Network error.");
                                break;
                            case ROUTE_CANCELED:
                                displayMessage("Error starting navigation: Route canceled.");
                                break;
                            default:
                                displayMessage("Error starting navigation: "
                                        + String.valueOf(code));
                        }
                    }
                });
    }

アプリをビルドして実行する

  1. Android デバイスをコンピュータに接続します。Android Studio の手順に沿って、ハードウェア デバイスでアプリを実行する方法を行います。または、Android Virtual Device(AVD)Manager を使用して仮想デバイスを構成することもできます。エミュレータを選択する際は、Google API が含まれているイメージを選択してください。
  2. Android Studio で、[Run] メニュー オプションまたは再生ボタンアイコンをクリックします。表示される指示に沿ってデバイスを選択します。

ユーザー エクスペリエンスの向上に関するヒント

  • ナビゲーションを使用できるようにするには、ユーザーが Google ナビゲーションの利用規約に同意する必要があります。この承認は 1 回のみ必要です。デフォルトでは、ナビゲータが初めて呼び出されると、SDK から承認を求めるメッセージが表示されます。必要に応じて、TermsAndConditionsCheckOption を使用して、アプリの UX フローの早い段階(登録時やログイン時など)でナビゲーション利用規約ダイアログをトリガーできます。
  • ナビゲーションの品質と到着予定時刻の精度を大幅に改善するには、緯度/経度座標ではなく、プレイス ID を使用してウェイポイントを初期化します。
  • このサンプルでは、シドニー オペラハウスの特定の場所 ID から目的地のウェイポイントを導出します。場所 ID 検索ツールを使用して、他の特定の場所の場所 ID を取得できます。