请按照本指南使用 Android 版 Navigation SDK 在应用中绘制路线。本指南假定您已按照设置项目中所述的方式将 Navigation SDK 集成到您的应用中。
摘要
- 将界面元素添加到应用中,以导航 fragment 或导航视图的形式。此界面元素会将交互式地图和精细导航界面添加到您的 activity。
- 请求位置信息权限。您的应用必须请求位置信息权限,才能确定设备的位置。
- 使用
NavigationApi
类初始化 SDK。 使用
Navigator
类设置目的地并控制精细导航。此过程包括以下三个步骤:- 使用
setDestination()
设置目的地。 - 使用
startGuidance()
开始导航。 - 使用
getSimulator()
模拟车辆沿路线的进度,以便测试、调试和演示应用。
- 使用
构建并运行您的应用。
查看代码
显示或隐藏单目的地导航 activity 的 Java 代码。
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); } }
向应用添加界面元素
本部分介绍了添加用于显示精细导航路线的交互式地图和界面的两种方法。在大多数情况下,我们建议使用 SupportNavigationFragment
(即 NavigationView
的封装容器),而不是直接与 NavigationView
交互。如需了解详情,请参阅导航地图互动最佳实践
。
使用导航 fragment
SupportNavigationFragment
是用于显示导航视觉输出的界面组件,包括交互式地图和精细导航路线。您可以在 XML 布局文件中声明 fragment,如下所示:
<?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"/>
或者,您也可以使用 FragmentActivity.getSupportFragmentManager()
以编程方式构建 fragment,如 Android 文档中所述。
使用导航视图
作为 fragment 的替代方案,用于显示导航地图的界面组件也可作为 NavigationView
使用。
请求位置权限
本部分介绍了如何请求精确位置信息权限。如需了解详情,请参阅 Android 权限指南。
在 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>
在您的应用中请求运行时权限,让用户有机会授予或拒绝位置信息权限。以下代码会检查用户是否已授予精确位置信息权限。如果未授予,它将请求此权限:
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; }
替换
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 导航栏。本部分介绍了如何初始化导航器,以及您可以为应用启用的其他一些配置:
初始化 Navigation SDK 并替换
onNavigatorReady()
回调,以便在导航器准备就绪时启动导航。可选。请配置应用,以便在用户从设备上关闭应用时关闭引导通知和后台服务。此选择取决于您的业务模式。您可能需要使用默认的导航器行为,即即使应用关闭,导航器也会继续显示转弯指示和位置信息更新。相反,如果您想在最终用户关闭应用时关闭导航和位置信息更新,则应使用此配置。
可选。在受支持的国家/地区启用道路限行功能。设置车牌号码的最后一位数字。此调用只需执行一次:后续的路线请求会继续使用它。此通话仅适用于受支持的地区。请参阅 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));
}
}
});
}
构建并运行应用
- 将 Android 设备连接到您的计算机。按照 Android Studio 中的说明了解如何在硬件设备上运行应用。或者,您也可以使用 Android 虚拟设备 (AVD) 管理器配置虚拟设备。选择模拟器时,请务必选择包含 Google API 的映像。
- 在 Android Studio 中,点击 Run 菜单选项或“Play”按钮图标。按提示选择设备。
有关如何提升用户体验的提示
- 用户必须先接受《Google 导航服务条款》,然后才能使用导航功能。您只需接受一次即可。默认情况下,SDK 会在首次调用导航器时提示用户接受。如果您愿意,可以在应用用户体验流程的早期(例如注册或登录期间)使用
TermsAndConditionsCheckOption
触发导航服务条款对话框。 - 如需显著提高导航质量和预计到达时间 (ETA) 的准确性,请使用地点 ID 初始化航点,而不是使用经纬度坐标。
- 此示例根据悉尼歌剧院的特定地点 ID 派生出目的地航点。您可以使用地点 ID 查找工具获取其他特定地点的地点 ID。