Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

1.0 Navigation SDK Migration Guide

Erin Quinn edited this pageFeb 18, 2021 ·7 revisions

“The Mapbox Navigation SDK” is actually comprised of two SDKs that can be used to integrate navigation into your Android project:

  • The Navigation SDK. This is where core logic lives for generating routes, tracking route progress, delivering turn-by-turn instructions, and other actions related to Directions API information.
  • The Navigation UI SDK. Built on top of the Navigation SDK, the Navigation UI SDK consumes data from the Navigation SDK and arranges it in default UI components that have various customizable options.

Read the1.0 Navigation SDK’s entire documentation athttps://docs.mapbox.com/android/navigation/overview

Pricing changes

Applications built with v1.0.0+ are billed based only onmonthly active users, specifically"Navigation SDKs" MAUs which are described in more detail in theNavigation SDK for Android pricing guide. Navigation SDK MAUs include Directions API, Vector Tiles API, and Raster Tiles API requests with no upfront commitments or annual contracts. A single user is billed as one MAU across app upgrades as long as the app is not deleted. Deleting and re-installing an app that uses the Navigation SDK would result in an additional MAU. This happens because the SDK does not store personally identifying information. To see the number of Navigation SDKs MAUs included in the free tier and the cost per Navigation SDKs MAU beyond the free tier, see the Navigation SDKs section of ourpricing page.

About the 1.0 Navigation SDK:

The1.0 release of the SDK debuts code for a vastly more straightforward way of building a navigation experience. The SDK brings completely new features, including:

  • a higher accuracy location engine that functions even in low GPS quality scenarios such as tunnels or overpasses.

  • free drive capabilities. Also known as passive navigation, drivers can now navigate in a mode without a destination entered.

  • a comprehensive modular and extensible architecture exposing stable and performant APIs that are hard to misuse, allowing your developers options to integrate custom analytics or a custom router. As long as these modules follow the API definitions, they can be customized and easily integrated.

Kotlin:

The1.0 Navigation SDK is written 100% inKotlin. This is a change from how the pre-1.0 versions were written in Java.

Setting up the1.0 Navigation SDK

Please seehttps://docs.mapbox.com/android/navigation/overview/#installation for the most up-to-date instructions on installing the1.0 Navigation SDK.

Minimum Android SDK:

The Mapbox Android Navigation team has decided to bump the minimum Android SDK version to 21 for the1.0 SDK. Please make sure that your project’sminSdkVersion is set to 21 or higher in your application-levelbuild.gradle file.

android {    defaultConfig {        …        minSdkVersion21        …        …    }}

NavigationOptions

NavigationOptions is the1.0 version of the pre-1.0MapboxNavigationOptions class.NavigationOptions has aBuilder class and you can use theBuilder class to explore what methods are available for setting specific options such as your preferred units to use for distance and time.

val navigationOptions=NavigationOptions.Builder().distanceFormatter(MapboxDistanceFormatter.builder().withRoundingIncrement(Rounding.INCREMENT_FIFTY).withUnitType(VoiceUnit.METRIC).build(this)).timeFormatType(TWELVE_HOURS).build()

Once created, theNavigationOptions object should be used as a method parameter when initializing theMapboxNavigation class.

More information about theNavigationOptions class can be found athttps://docs.mapbox.com/android/navigation/overview/#set-navigationoptions.

MapboxNavigation:

Creating aMapboxNavigation object is the first step in interacting with and customizing a navigation session. It's used to request routes, register various Navigation SDK observers, and make other navigation-related decisions. It needs a context object as well as a validMapbox access token.

Create and use only one instance of this class in your project.

val navigation=MapboxNavigation.defaultNavigationOptions(context,MAPBOX_ACCESS_TOKEN)

Alternatively, use theMapboxNavigation's constructor if you'd like to set the various options yourself:

val mapboxNavigation=MapboxNavigation(applicationContext,mapboxNavigationOptions,LocationEngineProvider.getBestLocationEngine(this))

Don’t forget to callmapboxNavigation.onDestroy() in the lifecycleonDestroy() part of your Android project.

overridefunonDestroy() {super.onDestroy()        mapboxNavigation.onDestroy()}

More information about theMapboxNavigation class can be found athttps://docs.mapbox.com/android/navigation/overview/#create-a-mapboxnavigation-object

ROUTING

Requesting a route:

After you’ve created amapboxNavigation object, you can use itsrequestRoutes() method. The method requires a builtRouteOptions object. TheRouteOptions class has convenient methods for setting the various route parameters that can be found athttps://docs.mapbox.com/api/navigation/#directions. Despite the many builder methods, onlyaccessToken,origin, anddestination are required to build a valid route request.

mapboxNavigation.requestRoutes(RouteOptions.builder()    .accessToken(MAPBOX_TOKEN)    .coordinates(mutableListOf(originPoint, destinationPoint))    .geometries(RouteUrl.GEOMETRY_POLYLINE6)    .profile(RouteUrl.PROFILE_DRIVING)    .build())

More information athttps://docs.mapbox.com/android/navigation/overview/route-generation/#request-a-route

Route status:

ThemapboxNavigation.requestRoutes() method’s only required parameter is the builtRouteOptions object. An optional second parameter is aRoutesRequestCallback interface object. The1.0 Navigation SDK’sRoutesRequestCallback interface provides methods that inform you about the route request status.

val routesReqCallback=object:RoutesRequestCallback {overridefunonRoutesReady(routes:List<DirectionsRoute>) {    }overridefunonRoutesRequestFailure(throwable:Throwable,routeOptions:RouteOptions) {    }overridefunonRoutesRequestCanceled(routeOptions:RouteOptions) {            }}

You’ll typically wantnavigationMapboxMap to draw the first route returned inside ofonRoutesReady():

privateval routesReqCallback=object:RoutesRequestCallback {overridefunonRoutesReady(routes:List<DirectionsRoute>) {if (routes.isNotEmpty()) {            navigationMapboxMap?.drawRoute(routes[0])}    }overridefunonRoutesRequestFailure(throwable:Throwable,routeOptions:RouteOptions) {            }overridefunonRoutesRequestCanceled(routeOptions:RouteOptions) {            }}

More information athttps://docs.mapbox.com/android/navigation/overview/route-generation/#route-request-status

Changed routes:

Use the1.0 Navigation SDK’sRouteObserver interface if you want to know when the routes list has changed. Registering aRouteObserver interface object viamapboxNavigation.registerRouteObserver(routeObserver) is one way to do it. Alternatively, you can implement the interface, register the interface withmapboxNavigation.registerRouteObserver(this), and override the interface’s single method.

privateval routeObserver=object:RouteObserver {overridefunonRoutesChanged(routes:List<DirectionsRoute>) {    navigationMapRoute?.addRoutes(routes)    }}

More information athttps://docs.mapbox.com/android/navigation/overview/route-generation/#changed-routes

Listening to route progress:

ProgressChangeListener is the pre-1.0 interface callback for receiving information about where the device is along the directions route in turn-by-turn navigation mode.

RouteProgressObserver is the1.0 Navigation SDK’s equivalent interface. This new interface only has one method, which isonRouteProgressChanged(). The interface still returnsaRouteProgress object.

privateval routeProgressObserver=object:RouteProgressObserver {overridefunonRouteProgressChanged(routeProgress:RouteProgress) {           }}

Alternatively, you can implement the interface, register the interface withmapboxNavigation.registerRouteProgressObserver(this), and override the interface’s method.

Don’t forget to unregister the interface!

overridefunonStop() {super.onStop()    mapView.onStop()    mapboxNavigation.unregisterRouteProgressObserver(routeProgressObserver)}

More information athttps://docs.mapbox.com/android/navigation/overview/route-progress/

Optional faster route

FasterRouteObserver is the1.0 Nav SDK’s way to listen to the retrieval of a fasterDirectionsRoute.

The observer object:

privateval fasterRouteObserver=object:FasterRouteObserver {overridefunrestartAfterMillis()=FasterRouteObserver.DEFAULT_INTERVAL_MILLISoverridefunonFasterRoute(currentRoute:DirectionsRoute,alternatives:List<DirectionsRoute>,isAlternativeFaster:Boolean    ) {                    }}

Attach the observer interface:

mapboxNavigation.attachFasterRouteObserver(fasterRouteObserver)

Don’t forget to detach the observer interface!

overridefunonStop() {super.onStop()    mapView.onStop()    mapboxNavigation.detachFasterRouteObserver()}

More information athttps://docs.mapbox.com/android/navigation/overview/faster-route

LOCATION

1.0 introduces a new interface listener to use for receiving device location updates. TheLocationObserver’s two methods will fire whenever the device changes location. If you’re using the Navigation UI SDK, you don’thave to use theLocationObserver interface for a standard1.0 Navigation SDK setup. The Navigation UI SDK automatically handles displaying the device location puck on the map. The Navigation SDK doesn't include any UI pieces at all, except for the sticky foreground notification.

TheLocationObserver interface is optional and is available in case you want to track device location yourself and do anything with the returnedLocation object’s coordinates or altitude values.

privateval locationObserver=object:LocationObserver {overridefunonRawLocationChanged(rawLocation:Location) {                        }overridefunonEnhancedLocationChanged(enhancedLocation:Location,keyPoints:List<Location>    ) {            }}

Register the observer with theMapboxNavigation object:

mapboxNavigation.registerLocationObserver(locationObserver)

Don’t forget to unregister the interface!

overridefunonStop() {super.onStop()    mapView.onStop()    mapboxNavigation.unregisterLocationObserver(locationObserver)}

If you use theLocationObserver interface, be sure to also passfalse through theLocationComponent’suseDefaultLocationEngine() method so that you can eventually pass theonEnhancedLocationChanged() callback’sLocation object to theLocationComponent. Once you pass theLocation object, the Navigation SDK will use theLocationComponent to move the device location puck to the appropriate place on the map and make other adjustments.

mapboxMap.setStyle(Style.MAPBOX_STREETS) { style->    locationComponent= mapboxMap.locationComponent.apply {        activateLocationComponent(LocationComponentActivationOptions.builder(this, style)            .useDefaultLocationEngine(false)            .build()        )        cameraMode=CameraMode.TRACKING        isLocationComponentEnabled=true    }}

Passing theLocationComponent theLocation object returned byLocationObserver:

privateval locationObserver=object:LocationObserver {overridefunonRawLocationChanged(rawLocation:Location) {    }overridefunonEnhancedLocationChanged(enhancedLocation:Location,keyPoints:List<Location>    ) {locationComponent?.forceLocationUpdate(rawLocation)    }}

More information athttps://docs.mapbox.com/android/navigation/overview/device-location

About the 1.0 Navigation UI SDK

The1.0 UI SDK release as compared to legacy offers all the features but with a much finer control and granularity. This version mainly serves as a port of the legacy UI SDK implementation to use the1.0 version of the Navigation Core SDK and its features. The1.0 UI SDK also removes redundant methods & APIs while exposing new ones instead. The SDK also brings new features, including:

  • two different ways of providing feedback during a trip session, thereby helping Mapbox provide better route quality, turn-by-turn experiences, traffic congestion, etc.

  • allowing developers to deemphasize portions of the route line behind the puck, thereby reflecting route progress state.

  • providing UI components that visualize a single building footprint or extrusion. Great to use for marking the final destination in an improved arrival experience.

Namespace changes

The SDK introduces namespace changes for all the files. Make sure to change your import lines in your project’s files as well as any references to Navigation UI SDK widgets in yourxml files.

Internal package

The1.0 Navigation UI SDK moves some publicclass files to aninternal package. As the name suggests, these classes are meant to be only used internally. You should not use any of these classes’public methods as these files are subject to silent changes in the future without breaking Semver.

Setting up the1.0 Navigation UI SDK

Please see below for the most up-to-date instructions on installing the1.0 Navigation UI SDK.

Minimum Android SDK

The Mapbox Android Navigation team has decided to bump the minimum Android SDK version to 19 for the1.0 UI SDK. Please make sure that your project’sminSdkVersion is set to 19 or higher in your application-levelbuild.gradle file.

android {    defaultConfig {        …        minSdkVersion19        …        …    }}

The Navigation SDK uses Java 8 features. To enable Java 8 in your project, add the followingcompileOptions

android {    compileOptions {        sourceCompatibilityJavaVersion.VERSION_1_8        targetCompatibilityJavaVersion.VERSION_1_8    }}

Drop-In UI

Unlike the legacy UI SDK, the1.0 Navigation UI SDK removes the support ofNavigationLauncher andMapboxNavigtionActivity.NavigationLauncher made it easy for the developer to display turn-by-turn navigation UI using the route already retrieved from the core Mapbox Navigation SDK for Android.NavigationLauncher exposed Builder options to allow developers to configure route and navigation options. These options would then be inflated in theMapboxNavigationActivity. However, this approach imposed limitations in the sense that customizing properties and features on-the-fly was very difficult to achieve. Exposure toActivity didn’t allow for creating and registering custom observers and also runtime styling without affecting the lifecycle of the Activity.

Instead, if you want the1.0 Navigation UI SDK to display turn-by-turn UI for you, we encourage you to make use ofNavigationView. TheNavigationView should be familiar from the pre-1.0.0 versions of the Navigation UI SDK and it gives you more control over styling the UI components. It also provides various callbacks to deliver relevant information. Please see theNavigationViewActivity andNavigationViewFragmentActivity examples forActivity andFragment based implementations.

Routes

If you are using theNavigationView component of the UI SDK, you would need to fetch the route using the Core SDK first and then supply it usingNavigationViewOptions. Refer tohttps://github.com/mapbox/mapbox-navigation-android/wiki/1.0-Navigation-SDK-Migration-Guide#routing for information on fetching route.

Once you are in active navigation mode and you reroute for any reasons,NavigationView would handle the reroute event. If you are not using theNavigationView, you would have to observe the reroute event and make appropriate changes to your UI, like callingNavigationMapboxMap#drawRoutes.

Styling

The1.0 Navigation UI SDK exposes the ability for developers to style the UI widgets regardless of whether the widgets are being used independently or within theNavigationView. These UI widgets include:

  • InstructionView
  • SummaryBottomSheet
  • RecenterButton
  • WayNameView
  • MapRouteLine
  • NavigationMapRoute

For example, if you want to style theRecenterButton:

In your project’svalues/styles.xml file:

<style name="CustomRecenterButton"><!--Recenter button background color--><item name="recenterButtonPrimaryColor">@color/navigation_primary_background</item><!--Recenter button text color--><item name="recenterButtonSecondaryColor">@color/navigation_accent</item></style>

To apply the style, add theRecenterButton to your project’sxml file where you are using the Navigation UI SDK’sRecenterButton.

<com.mapbox.navigation.ui.RecenterButtonandroid:id="@+id/recenterBtn"style="@style/CustomRecenterButton"android:layout_width="wrap_content"android:layout_height="wrap_content" />

Look at theCustomUIComponentStyleActivity example in the Navigation UI SDK’s repository for more details on custom styling of components.

Voice Instructions:

1.0 removes the support ofVoiceInstructionMilestone andMilestoneEventListener. Now it exposes aVoiceInstructionObserver that triggersonNewVoiceInstructions() every time a new voice instruction is available.

Inside yourActivity orFragment:

privateval voiceInstructionsObserver=object:VoiceInstructionsObserver {overridefunonNewVoiceInstructions(voiceInstructions:VoiceInstructions) {// play voice instructions    }}overridefunonCreate(savedInstanceState:Bundle?) {    mapboxNavigation=MapboxNavigation(        applicationContext,        mapboxNavigationOptions,        locationEngine= getLocationEngine()    ).apply {        registerVoiceInstructionsObserver(voiceInstructionsObserver)    }}overridefunonDestroy() {super.onDestroy()    mapboxNavigation?.apply {        unregisterVoiceInstructionsObserver(voiceInstructionsObserver)    }    mapboxNavigation.onDestroy()}

Similarly,SpeechAnnouncement has been removed and replaced byVoiceInstructions.

Banner Instructions:

1.0 exposes aBannerInstructionsObserver that triggersonNewBannerInstructions() every time a new banner instruction is available. It acts as the data source containing maneuver information that’s helpful in turn-by-turn navigation.

Inside yourActivity orFragment:

privateval bannerInstructionObserver=object:BannerInstructionsObserver {overridefunonNewBannerInstructions(bannerInstructions:BannerInstructions) {// update banner        }    }overridefunonCreate(savedInstanceState:Bundle?) {    mapboxNavigation=MapboxNavigation(        applicationContext,        mapboxNavigationOptions,        locationEngine= getLocationEngine()    ).apply {        registerBannerInstructionsObserver(bannerInstructionObserver)    }}overridefunonDestroy() {super.onDestroy()    mapboxNavigation?.apply {        unregisterBannerInstructionsObserver(bannerInstructionObserver)    }    mapboxNavigation.onDestroy()}

Feedback:

1.0 enables developers to allow their users to send feedback in two different ways. A user can now send feedback detailing the issue during turn-by-turn navigation.

To allow your user just to be able to report problem:

FeedbackBottomSheet.newInstance(object:FeedbackBottomSheetListener {overridefunonFeedbackSelected(feedbackItem:FeedbackItem?) {MapboxNavigation.postUserFeedback(...)        }overridefunonFeedbackDismissed() {// handle events when feedback is dismissed        }    },FeedbackBottomSheet.FEEDBACK_MAIN_FLOW,0L// FeedbackBottomSheet duration in Long).show(it,FeedbackBottomSheet.TAG)

To allow your user to go one step deeper to submit more details about the problem:

FeedbackBottomSheet.newInstance(    object : FeedbackBottomSheetListener {        override fun onFeedbackSelected(feedbackItem: FeedbackItem?) {            MapboxNavigation.postUserFeedback(...)        }        override fun onFeedbackDismissed() {            // handle events when feedback is dismissed        }    },    FeedbackBottomSheet.FEEDBACK_DETAIL_FLOW,    0L // FeedbackBottomSheet duration in Long).show(it, FeedbackBottomSheet.TAG)

For further information on how to use Navigation UI SDK1.0, you can refer tothese examples.

Next steps

Again, not all of the Navigation SDK’s new features are covered in this migration guide. This guide makes assumptions about what parts of the Navigation SDK a simple and barebones navigation project will use.

Read the Navigation SDK’s complete documentation athttp://docs.mapbox.com/android/navigation/overview.

Questions?

If you’ve got any questions, please reach out to the Mapbox team viahttps://github.com/mapbox/mapbox-navigation-android/issues/new.

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp