メインコンテンツまでスキップ

Render building extrusion on arrival

Note

This example is a part of the Navigation SDK Examples. You can find the values for all referenced resources in the res directory. For example, see res/values/strings.xml for R.string.* references used in this example. The dependencies can be found here.The examples use View binding.See setup documention if necessary.

mapbox_activity_building_extrusions
<?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"
xmlns:tools="http://schemas.android.com/tools"
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_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<androidx.appcompat.widget.AppCompatButton
android:id="@+id/actionButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:background="@drawable/mapbox_button"
android:padding="12dp"
android:text="Fetch Route"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="HardcodedText" />

</androidx.constraintlayout.widget.ConstraintLayout>
ShowBuildingExtrusionsActivity.kt
package com.mapbox.navigation.examples.standalone.building

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.mapbox.api.directions.v5.models.RouteOptions
import com.mapbox.bindgen.Expected
import com.mapbox.common.location.Location
import com.mapbox.geojson.Point
import com.mapbox.maps.CameraOptions
import com.mapbox.maps.EdgeInsets
import com.mapbox.maps.MapboxMap
import com.mapbox.maps.logE
import com.mapbox.maps.plugin.animation.MapAnimationOptions
import com.mapbox.maps.plugin.animation.camera
import com.mapbox.maps.plugin.locationcomponent.location
import com.mapbox.navigation.base.ExperimentalPreviewMapboxNavigationAPI
import com.mapbox.navigation.base.extensions.applyDefaultNavigationOptions
import com.mapbox.navigation.base.extensions.applyLanguageAndVoiceUnitOptions
import com.mapbox.navigation.base.options.NavigationOptions
import com.mapbox.navigation.base.route.NavigationRoute
import com.mapbox.navigation.base.route.NavigationRouterCallback
import com.mapbox.navigation.base.route.RouterFailure
import com.mapbox.navigation.base.route.RouterOrigin
import com.mapbox.navigation.base.trip.model.RouteLegProgress
import com.mapbox.navigation.base.trip.model.RouteProgress
import com.mapbox.navigation.core.MapboxNavigation
import com.mapbox.navigation.core.arrival.ArrivalObserver
import com.mapbox.navigation.core.directions.session.RoutesObserver
import com.mapbox.navigation.core.lifecycle.MapboxNavigationApp
import com.mapbox.navigation.core.lifecycle.MapboxNavigationObserver
import com.mapbox.navigation.core.lifecycle.requireMapboxNavigation
import com.mapbox.navigation.core.replay.route.ReplayProgressObserver
import com.mapbox.navigation.core.replay.route.ReplayRouteMapper
import com.mapbox.navigation.core.trip.session.LocationMatcherResult
import com.mapbox.navigation.core.trip.session.LocationObserver
import com.mapbox.navigation.examples.databinding.MapboxActivityBuildingExtrusionsBinding
import com.mapbox.navigation.examples.standalone.camera.ShowCameraTransitionsActivity
import com.mapbox.navigation.examples.standalone.routeline.RenderRouteLineActivity
import com.mapbox.navigation.ui.base.util.MapboxNavigationConsumer
import com.mapbox.navigation.ui.maps.NavigationStyles
import com.mapbox.navigation.ui.maps.building.api.MapboxBuildingsApi
import com.mapbox.navigation.ui.maps.building.model.BuildingError
import com.mapbox.navigation.ui.maps.building.model.BuildingValue
import com.mapbox.navigation.ui.maps.building.view.MapboxBuildingView
import com.mapbox.navigation.ui.maps.location.NavigationLocationProvider
import com.mapbox.navigation.ui.maps.route.arrow.api.MapboxRouteArrowApi
import com.mapbox.navigation.ui.maps.route.arrow.api.MapboxRouteArrowView
import com.mapbox.navigation.ui.maps.route.line.api.MapboxRouteLineApi
import com.mapbox.navigation.ui.maps.route.line.api.MapboxRouteLineView
import com.mapbox.navigation.ui.maps.route.line.model.MapboxRouteLineApiOptions
import com.mapbox.navigation.ui.maps.route.line.model.MapboxRouteLineViewOptions
import java.util.Date

/**
* The example demonstrates how to extrude a building upon reaching a waypoint and final destination.
*
* Before running the example make sure you have put your access_token in the correct place
* inside [app/src/main/res/values/mapbox_access_token.xml]. If not present then add this file
* at the location mentioned above and add the following content to it
*
* <?xml version="1.0" encoding="utf-8"?>
* <resources xmlns:tools="http://schemas.android.com/tools">
* <string name="mapbox_access_token"><PUT_YOUR_ACCESS_TOKEN_HERE></string>
* </resources>
*
* The example assumes that you have granted location permissions and does not enforce it. However,
* the permission is essential for proper functioning of this example. The example also uses replay
* location engine to facilitate navigation without actually physically moving.
*
* The example uses camera API's exposed by the Maps SDK rather than using the API's exposed by the
* Navigation SDK. This is done to make the example concise and keep the focus on actual feature at
* hand. To learn more about how to use the camera API's provided by the Navigation SDK look at
* [ShowCameraTransitionsActivity]
*
* How to use this example:
* - The example uses a list of predefined coordinates that will be used to fetch a route.
* - When the example starts, the camera transitions to the location where the route origin is.
* - Click on Fetch Route to fetch a route and start navigation.
* - You should now start to navigate and see building extrusion once when you reach the waypoint
* and again when you reach the final destination.
*
* Note:
* The example does not demonstrate the use of [MapboxRouteArrowApi] and [MapboxRouteArrowView].
* Take a look at [RenderRouteLineActivity] example to learn more about route line and route arrow.
*/
@OptIn(ExperimentalPreviewMapboxNavigationAPI::class)
class ShowBuildingExtrusionsActivity : AppCompatActivity() {

private val routeCoordinates = listOf(
Point.fromLngLat(-122.4192, 37.7627),
Point.fromLngLat(-122.4183502, 37.7653577),
Point.fromLngLat(-122.4145371, 37.7657253),
)

/**
* Debug observer that makes sure the replayer has always an up-to-date information to generate mock updates.
*/
private lateinit var replayProgressObserver: ReplayProgressObserver

/**
* [NavigationLocationProvider] is a utility class that helps to provide location updates generated by the Navigation SDK
* to the Maps SDK in order to update the user location indicator on the map.
*/
private val navigationLocationProvider = NavigationLocationProvider()

/**
* Bindings to the example layout.
*/
private lateinit var binding: MapboxActivityBuildingExtrusionsBinding

/**
* Generates updates for the [MapboxBuildingView] by querying a building feature if it exists
* on a [MapboxMap]
*/
private lateinit var buildingApi: MapboxBuildingsApi

/**
* A view that allows you to extrudes a building of interest by querying it on the [MapboxMap]
* using [MapboxBuildingsApi]
*/
private val buildingView = MapboxBuildingView()

/**
* The callback contains a list of buildings returned as a result of querying the [MapboxMap].
* If no buildings are available, the list is empty
*/
private val callback =
MapboxNavigationConsumer<Expected<BuildingError, BuildingValue>> { expected ->
expected.fold(
{
logE(
"ShowBuildingExtrusionsActivity",
"error: ${it.errorMessage}"
)
},
{ value ->
binding.mapView.mapboxMap.getStyle { style ->
buildingView.highlightBuilding(style, value.buildings)
}
}
)
}

/**
* Additional route line options are available through the
* [MapboxRouteLineViewOptions] and [MapboxRouteLineApiOptions].
*/
private val options: MapboxRouteLineViewOptions by lazy {
MapboxRouteLineViewOptions.Builder(this)
.routeLineBelowLayerId("road-label-navigation")
.build()
}

private val routeLineApiOptions: MapboxRouteLineApiOptions by lazy {
MapboxRouteLineApiOptions.Builder()
.build()
}

/**
* This class is responsible for rendering route line related mutations generated by the [routeLineApi]
*/
private val routeLineView by lazy {
MapboxRouteLineView(options)
}

/**
* Generates updates for the [routeLineView] with the geometries and properties of the routes that should be drawn on the map.
*/
private val routeLineApi: MapboxRouteLineApi by lazy {
MapboxRouteLineApi(routeLineApiOptions)
}

/**
* Gets notified with location updates.
*
* Exposes raw updates coming directly from the location services
* and the updates enhanced by the Navigation SDK (cleaned up and matched to the road).
*/
private val locationObserver = object : LocationObserver {
/**
* Invoked as soon as the [Location] is available.
*/
override fun onNewRawLocation(rawLocation: Location) {
// Not implemented in this example. However, if you want you can also
// use this callback to get location updates, but as the name suggests
// these are raw location updates which are usually noisy.
}

/**
* Provides the best possible location update, snapped to the route or
* map-matched to the road if possible.
*/
override fun onNewLocationMatcherResult(locationMatcherResult: LocationMatcherResult) {
val enhancedLocation = locationMatcherResult.enhancedLocation
navigationLocationProvider.changePosition(
enhancedLocation,
locationMatcherResult.keyPoints,
)
// Invoke this method to move the camera to your current location.
updateCamera(
Point.fromLngLat(
enhancedLocation.longitude,
enhancedLocation.latitude
),
enhancedLocation.bearing
)
}
}

/**
* This is one way to keep the route(s) appearing on the map in sync with
* MapboxNavigation. When this observer is called the route data is used to draw route(s)
* on the map.
*/
private val routesObserver: RoutesObserver = RoutesObserver { routeUpdateResult ->
routeLineApi.setNavigationRoutes(
routeUpdateResult.navigationRoutes
) { value ->
binding.mapView.mapboxMap.style?.apply {
routeLineView.renderRouteDrawData(this, value)
}
}
}

private val arrivalObserver: ArrivalObserver = object : ArrivalObserver {
override fun onFinalDestinationArrival(routeProgress: RouteProgress) {
buildingApi.queryBuildingOnFinalDestination(routeProgress, callback)
}

override fun onNextRouteLegStart(routeLegProgress: RouteLegProgress) {
binding.mapView.mapboxMap.getStyle { style ->
buildingView.removeBuildingHighlight(style)
}
}

override fun onWaypointArrival(routeProgress: RouteProgress) {
buildingApi.queryBuildingOnWaypoint(routeProgress, callback)
}
}

private val mapboxNavigation: MapboxNavigation by requireMapboxNavigation(
onResumedObserver = object : MapboxNavigationObserver {
@SuppressLint("MissingPermission")
override fun onAttached(mapboxNavigation: MapboxNavigation) {
mapboxNavigation.registerRoutesObserver(routesObserver)
mapboxNavigation.registerArrivalObserver(arrivalObserver)
mapboxNavigation.registerLocationObserver(locationObserver)

replayProgressObserver = ReplayProgressObserver(mapboxNavigation.mapboxReplayer)
mapboxNavigation.registerRouteProgressObserver(replayProgressObserver)

mapboxNavigation.startReplayTripSession()
}

override fun onDetached(mapboxNavigation: MapboxNavigation) {
mapboxNavigation.unregisterRoutesObserver(routesObserver)
mapboxNavigation.unregisterArrivalObserver(arrivalObserver)
mapboxNavigation.unregisterLocationObserver(locationObserver)
mapboxNavigation.unregisterRouteProgressObserver(replayProgressObserver)
mapboxNavigation.mapboxReplayer.finish()
}
},
onInitialize = this::initNavigation
)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = MapboxActivityBuildingExtrusionsBinding.inflate(layoutInflater)
setContentView(binding.root)

binding.mapView.mapboxMap.loadStyle(NavigationStyles.NAVIGATION_DAY_STYLE) {
binding.actionButton.visibility = View.VISIBLE
}

binding.actionButton.setOnClickListener {
binding.actionButton.visibility = View.GONE
fetchRoute()
}

buildingApi = MapboxBuildingsApi(binding.mapView.mapboxMap)
}

override fun onDestroy() {
super.onDestroy()
buildingApi.cancel()
routeLineView.cancel()
routeLineApi.cancel()
}

private fun updateCamera(point: Point, bearing: Double? = null) {
val mapAnimationOptions = MapAnimationOptions.Builder().duration(1500L).build()
binding.mapView.camera.easeTo(
CameraOptions.Builder()
// Centers the camera to the lng/lat specified.
.center(point)
// specifies the zoom value. Increase or decrease to zoom in or zoom out
.zoom(17.0)
// adjusts the bearing of the camera measured in degrees from true north
.bearing(bearing)
// adjusts the pitch towards the horizon
.pitch(45.0)
// specify frame of reference from the center.
.padding(EdgeInsets(1000.0, 0.0, 0.0, 0.0))
.build(),
mapAnimationOptions
)
}

private fun initNavigation() {
MapboxNavigationApp.setup(
NavigationOptions.Builder(this)
.build()
)

binding.mapView.location.apply {
setLocationProvider(navigationLocationProvider)
enabled = true
}

replayOriginLocation()
}

private fun fetchRoute() {
mapboxNavigation.requestRoutes(
RouteOptions.builder()
.applyDefaultNavigationOptions()
.applyLanguageAndVoiceUnitOptions(this)
.alternatives(false)
.coordinatesList(routeCoordinates)
.layersList(listOf(mapboxNavigation.getZLevel(), null, null))
.build(),

object : NavigationRouterCallback {
override fun onRoutesReady(
routes: List<NavigationRoute>,
@RouterOrigin routerOrigin: String
) {
mapboxNavigation.setNavigationRoutes(routes)
}

override fun onFailure(
reasons: List<RouterFailure>,
routeOptions: RouteOptions
) {
Log.d(LOG_TAG, "onFailure: $reasons")
}

override fun onCanceled(
routeOptions: RouteOptions,
@RouterOrigin routerOrigin: String
) {
Log.d(LOG_TAG, "onCanceled")
}
}
)
}

private fun replayOriginLocation() {
with(mapboxNavigation.mapboxReplayer) {
play()
pushEvents(
listOf(
ReplayRouteMapper.mapToUpdateLocation(
Date().time.toDouble(),
routeCoordinates.first()
)
)
)
playFirstLocation()
playbackSpeed(3.0)
}
}

private companion object {
val LOG_TAG: String = ShowBuildingExtrusionsActivity::class.java.simpleName
}
}
この{Type}は役に立ちましたか?