导航单目的地路线

请按照本指南在应用中绘制路线, 适用于 Android 的 Navigation SDK。本指南假定您已经集成了 Navigation SDK 导入您的应用,如 设置您的项目

摘要

  1. 将界面元素作为导航 Fragment 或 导航视图。此界面元素可添加交互式地图和精细导航 导航界面。
  2. 请求位置信息权限。您的应用必须请求位置信息权限 以确定设备的位置。
  3. 使用以下命令初始化 SDK: NavigationApi 类。
  4. 使用 Navigator 类。这涉及以下三个步骤:

  5. 构建并运行您的应用。

查看代码

向应用添加界面元素

本部分介绍了两种方法,可用于为 Google 地图和 Google 地图 精细导航功能。

SupportNavigationFragment 是用于显示导航的视觉输出的界面组件,包括 交互式地图和精细导航路线。您可以在 如下所示:

<?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"/>

或者,您也可以通过编程方式构建 fragment,如 Android 文档,了解如何使用 FragmentActivity.getSupportFragmentManager()

用于显示地图的界面组件(作为 Fragment 的替代组件) 导航功能 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. 可选。在支持的国家/地区启用道路限制。设置最后一个 车牌的数字。此调用仅需进行一次:后续 路线请求会继续使用它。此通话仅支持受支持的设备 区域。请参阅 支持 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 虚拟设备 (AVD) 管理器。 选择模拟器时,请务必选择一个包含 Google API。
  2. 在 Android Studio 中,点击 Run 菜单选项或 Play 按钮图标。 按提示选择设备。

有助于改善用户体验的提示

  • 用户必须先接受 Google 导航服务条款, 导航功能可用。您只需接受一次。修改者 默认情况下,SDK 会在导航器首次 调用。如果您愿意,可以触发“导航服务条款”对话框 在应用用户体验流程的早期阶段(例如注册或登录期间)使用 TermsAndConditionsCheckOption
  • 要显著提高导航质量和预计到达时间的准确性,请使用 用地点 ID 初始化航点,而不是初始化纬度/经度 坐标。
  • 此示例根据 悉尼歌剧院。您可以使用 地点 ID 查找工具 其他特定营业地点的地点 ID。