Speed limit
The Mapbox Navigation SDK allows you to present speed limit information in your application using a pre-built UI component.
Use the default speed limit UI component
The default speed limit UI component, MapboxSpeedInfoView
, displays the speed limit of the road the user is traveling on.
Render the speed limit of the current road using the Speed Limit API and MapboxSpeedLimitView
.
Add the view to the layout
Start by adding the MapboxSpeedInfoView
to your activity or fragment layout. The sample code below positions the speed limit UI component on top of a map.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.maps.MapView
android:id="@+id/mapView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
<com.mapbox.navigation.ui.components.speedlimit.view.MapboxSpeedInfoView
android:id="@+id/speedLimitView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/mapbox_dimen_8dp"
android:layout_marginBottom="@dimen/mapbox_dimen_8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Create an instance of the Speed Limit API
The Speed Limit API formats speed limit data to be used in the speed limit UI component.
Create an instance of MapboxSpeedInfoApi
.
// Define distance formatter options
private val distanceFormatterOptions: DistanceFormatterOptions by lazy {
DistanceFormatterOptions.Builder(context).build()
}
// Create an instance of the Speed Info API
private val speedInfoApi: MapboxSpeedInfoApi by lazy {
MapboxSpeedInfoApi()
}
Start receiving map matching events
The updates for the speed limit component are powered by the LocationObserver
. Create an observer in your activity or fragment and register it with MapboxNavigation
. Be sure to unregister the LocationObserver
in either onStop
or onDestroy
to avoid leaking resources.
private val locationObserver = object : LocationObserver {
override fun onNewRawLocation(rawLocation: Location) {
...
}
override fun onNewLocationMatcherResult(
locationMatcherResult: LocationMatcherResult
) {
val value = speedInfoApi.updatePostedAndCurrentSpeed(
locationMatcherResult.speedLimit,
distanceFormatterOptions,
)
speedInfoView.render(value)
}
}
MapboxSpeedInfoApi
will be null.