mapbox 导航记录(release-v2.15分支 纯kotlin)

这篇具有很好参考价值的文章主要介绍了mapbox 导航记录(release-v2.15分支 纯kotlin)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、简单使用示例

1. 初始化 MapboxNavigation

初始化时使用 NavigationOptions 设置一些参数,包括accessToken、appMetaData、LocationEngine等,其它还有很多,具体可以详看 NavigationOptions 类的内部。

下面示例中 LocationEngine 使用的重演定位引擎,可以看到模拟导航的效果,关键的两个类就是 ReplayLocationEngine 和 MapboxReplayer 。

/* ----- Mapbox Navigation components ----- */
private lateinit var mapboxNavigation: MapboxNavigation

private val mapboxReplayer = MapboxReplayer()

// initialize Mapbox Navigation
mapboxNavigation = MapboxNavigationProvider.create(
    NavigationOptions.Builder(applicationContext)
        .accessToken(getMapboxAccessTokenFromResources())
        .eventsAppMetadata(
            EventsAppMetadata.Builder(
                    BuildConfig.APPLICATION_ID,
                    BuildConfig.VERSION_NAME
                ).build()
            )
        .locationEngine(ReplayLocationEngine(mapboxReplayer))
        .build()
)

2. 初始化 LocationObserver,对位置改变做观察

navigationLocationProvider 只是把当前导航的位置点给到 MapView,实现地图移动或者加位置图标等。

MapboxNavigationViewportDataSource 也是一样,移动地图的Camera到一个合适的位置,要结合 NavigationCamera 使用。NavigationCamera 还可以改变导航是 Following 还是 Overview 。

// camera
private lateinit var navigationCamera: NavigationCamera
private lateinit var viewportDataSource: MapboxNavigationViewportDataSource

// initialize Navigation Camera
viewportDataSource = MapboxNavigationViewportDataSource(
    binding.mapView.getMapboxMap()
)
navigationCamera = NavigationCamera(
    binding.mapView.getMapboxMap(),
    binding.mapView.camera,
    viewportDataSource
)

/* ----- Location and route progress callbacks ----- */
private val locationObserver = object : LocationObserver {
    override fun onNewRawLocation(rawLocation: Location) {
        // not handled
    }

    override fun onNewLocationMatcherResult(locationMatcherResult: LocationMatcherResult) {
        // update location puck's position on the map
        navigationLocationProvider.changePosition(
            location = locationMatcherResult.enhancedLocation,
            keyPoints = locationMatcherResult.keyPoints,
        )

        // update camera position to account for new location
        viewportDataSource.onLocationChanged(locationMatcherResult.enhancedLocation)
        viewportDataSource.evaluate()
    }
}

3. 初始化 RoutesObserver,对多条路线的处理

private val routesObserver = RoutesObserver { result ->
        if (result.routes.isNotEmpty()) {
            // generate route geometries asynchronously and render them
            CoroutineScope(Dispatchers.Main).launch {
                val result = routeLineAPI.setRoutes(
                    listOf(RouteLine(result.routes.first(), null))
                )
                val style = mapboxMap.getStyle()
                if (style != null) {
                    routeLineView.renderRouteDrawData(style, result)
                }
            }

            // update the camera position to account for the new route
            viewportDataSource.onRouteChanged(result.routes.first())
            viewportDataSource.evaluate()
        } else {
            // remove the route line and route arrow from the map
            val style = mapboxMap.getStyle()
            if (style != null) {
                routeLineAPI.clearRouteLine { value ->
                    routeLineView.renderClearRouteLineValue(
                        style,
                        value
                    )
                }
                routeArrowView.render(style, routeArrowAPI.clearArrows())
            }

            // remove the route reference to change camera position
            viewportDataSource.clearRouteData()
            viewportDataSource.evaluate()
        }
}

4. 初始化 NavigationSessionStateObserver ,对导航状态的监测

private val navigationSessionStateObserver = NavigationSessionStateObserver {
    logD("NavigationSessionState=$it", LOG_CATEGORY)
    logD("sessionId=${mapboxNavigation.getNavigationSessionState().sessionId}", LOG_CATEGORY)
}

5. 初始化 RouteProgressObserver ,对导航进度的监测

最关键的部分,如下是正常导航时的进度处理。但是对于模拟导航,只需要实例化 ReplayProgressObserver 对象。

// 模拟导航使用
private val routeProgressObserver1 = ReplayProgressObserver(mapboxReplayer)

// 正常导航使用
    private val routeProgressObserver =
        RouteProgressObserver { routeProgress ->
            // update the camera position to account for the progressed fragment of the route
            viewportDataSource.onRouteProgressChanged(routeProgress)
            viewportDataSource.evaluate()

            // show arrow on the route line with the next maneuver
            val maneuverArrowResult = routeArrowAPI.addUpcomingManeuverArrow(routeProgress)
            val style = mapboxMap.getStyle()
            if (style != null) {
                routeArrowView.renderManeuverUpdate(style, maneuverArrowResult)
            }

            // update top maneuver instructions
            val maneuvers = maneuverApi.getManeuvers(routeProgress)
            maneuvers.fold(
                { error ->
                    Toast.makeText(
                        this@MapboxNavigationActivity,
                        error.errorMessage,
                        Toast.LENGTH_SHORT
                    ).show()
                },
                {
                    binding.maneuverView.visibility = VISIBLE
                    binding.maneuverView.renderManeuvers(maneuvers)
                }
            )

            // update bottom trip progress summary
            binding.tripProgressView.render(tripProgressApi.getTripProgress(routeProgress))
        }

6. 初始化 VoiceInstructionsObserver ,对语音指令的监测

// 语音播报对象
private lateinit var voiceInstructionsPlayer: MapboxVoiceInstructionsPlayer

voiceInstructionsPlayer = MapboxVoiceInstructionsPlayer(
    this,
    Locale.US.language
)

// 静音和取消静音
voiceInstructionsPlayer.volume(SpeechVolume(0f))
voiceInstructionsPlayer.volume(SpeechVolume(1f))

/* ----- Voice instruction callbacks ----- */
private val voiceInstructionsObserver =
    VoiceInstructionsObserver { voiceInstructions ->
        speechAPI.generate(
            voiceInstructions,
            speechCallback
        )
    }

// speechCallback 中做 play
private val speechCallback =
        MapboxNavigationConsumer<Expected<SpeechError, SpeechValue>> { expected ->
            expected.fold(
                { error ->
                    // play the instruction via fallback text-to-speech engine
                    voiceInstructionsPlayer.play(
                        error.fallback,
                        voiceInstructionsPlayerCallback
                    )
                },
                { value ->
                    // play the sound file from the external generator
                    voiceInstructionsPlayer.play(
                        value.announcement,
                        voiceInstructionsPlayerCallback
                    )
                }
            )
        }

7. findRoute并将路线设置给导航模块,然后开启导航

// findRoute
mapboxNavigation.requestRoutes()

// 路线获取成功 onRoutesReady 后的处理
private fun setRouteAndStartNavigation(route: List<NavigationRoute>) {
    // set route
    mapboxNavigation.setNavigationRoutes(route)

    // show UI elements
    binding.soundButton.visibility = VISIBLE
    binding.routeOverview.visibility = VISIBLE
    binding.tripProgressCard.visibility = VISIBLE
    binding.routeOverview.showTextAndExtend(2000L)
    binding.soundButton.unmuteAndExtend(2000L)

    // move the camera to overview when new route is available
    navigationCamera.requestNavigationCameraToOverview()
}

override fun onStart() {
    super.onStart()
    mapboxNavigation.registerRoutesObserver(routesObserver)
    mapboxNavigation.registerNavigationSessionStateObserver(navigationSessionStateObserver)
//    mapboxNavigation.registerRouteProgressObserver(routeProgressObserver)
    mapboxNavigation.registerRouteProgressObserver(routeProgressObserver1)
    mapboxNavigation.registerLocationObserver(locationObserver)
    mapboxNavigation.registerVoiceInstructionsObserver(voiceInstructionsObserver)

    // 实际导航只需要注册好上面的观察者,下面时模拟导航的特殊开启方式
    mapboxReplayer.pushRealLocation(this, 0.0)
    mapboxReplayer.playbackSpeed(1.5)
    mapboxReplayer.play()
}

二、关键类

类名 所属模块 作用
MapboxNavigation libnavigation-core 核心类,要给它配置token,定位引擎等。
mapboxNavigation.startTripSession()
registerLocationObserver() 观察位置变化。
registerRoutesObserver() 对导航路线的处理,比如渲染,箭头等。
registerNavigationSessionStateObserver()
registerRouteProgressObserver() 导航进度。
registerVoiceInstructionsObserver() 语音指令。
NavigationOptions libnavigation-base 给 MapboxNavigation 配置token,定位引擎等使用此对象。
还有很多其它的配置项。
RoutesObserver libnavigation-core 对导航路线改变时,在这个接口方法中实现渲染。
RouteProgressObserver libnavigation-core 提供状态、进度和其他有关当前逐点路由的信息的回调。
LocationObserver libnavigation-core 监听位置更新。
VoiceInstructionsObserver libnavigation-core 语音指令接口。
----------------------------- ----------------------------- -----------------------------
MapboxNavigationViewportDataSource libnavui-maps UI相关,需要把 MapView 对象传递给此类。
NavigationCamera libnavui-maps UI相关,需要把 MapView,camera,MapboxNavigationViewportDataSource 对象传递给此类。
NavigationBasicGesturesHandler libnavui-maps UI相关,基础手势。
MapboxManeuverApi libnavui-maneuver UI相关,顶部显示还有多少米向左向右转等信息。
MapboxTripProgressApi libnavui-tripprogress UI相关,底部进度,剩余时间,剩余距离,当前时间。
MapboxSpeechApi libnavui-voice UI相关,语音部分。
MapboxVoiceInstructionsPlayer libnavui-voice UI相关,语音部分。
MapboxRouteLineApi libnavui-maps UI相关,路线上图相关。
MapboxRouteLineView libnavui-maps UI相关,路线上图相关。
MapboxRouteArrowView libnavui-maps UI相关,路线上图相关。
----------------------------- ----------------------------- -----------------------------
ReplayLocationEngine libnavigation-core 模拟导航相关类,要在NavigationOptions设置这种定位引擎
MapboxReplayer libnavigation-core 模拟导航相关类,控制模拟导航play,finish等
ReplayRouteMapper libnavigation-core 模拟导航相关类,利用它里面的方法把要模拟的路线对象DirectionsRoute设置进去
ReplayProgressObserver libnavigation-core 模拟导航相关类,观察模拟导航的进度,替代正常导航进度观察RouteProgressObserver

三、NavigationView

布局文件 mapbox_navigation_view_layout.xml

init { } 方法块中会创建MapView并添加到布局,利用mapLayoutCoordinator(binding) 实例化 MapLayoutCoordinator

再利用 MapLayoutCoordinator 里的方法给 core 模块中的 MapboxNavigation 绑定 MapView。

MapView 的创建使用 MapViewBinder,而对它设置样式使用 MapStyleLoader

四、获取导航路线 requestRoutes() 详细

MapboxNavigation 中获取导航路线的方法,有两个方法,参数有差异

fun requestRoutes(
    routeOptions: RouteOptions,
    routesRequestCallback: RouterCallback
)

fun requestRoutes(
    routeOptions: RouteOptions,
    callback: NavigationRouterCallback
)

RouterCallback 中获取导航路线成功得到的是 DirectionsRoute 集合,在模拟导航中使用 DirectionsRoute 对象。也对应结合 MapboxNavigation.setRoutes(List<DirectionsRoute>) 使用,方法内部会利用 toNavigationRoutes() 做转换。

NavigationRouterCallback 中获取导航路线成功得到的是 NavigationRoute 集合,对应结合 MapboxNavigation.setNavigationRoutes(List<NavigationRoute>) 使用。

toNavigationRoutes() 是把 DirectionsRoute 集合转为 NavigationRoute 集合,也有 toDirectionsRoutes() 可以把 NavigationRoute 集合转为 DirectionsRoute 集合。文章来源地址https://www.toymoban.com/news/detail-704406.html

到了这里,关于mapbox 导航记录(release-v2.15分支 纯kotlin)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Git开发、发布、缺陷分离模型概述(支持master/develop/feature/release/hotfix类型分支)

    Git是一种分布式版本控制系统,它可以记录文件的修改历史和版本变化,并可以支持多人协同开发。Git最初是由Linux开发者Linus Torvalds创建的,它具有高效、灵活、稳定等优点,如今已成为软件开发领域中最流行的版本控制系统之一。Git使用一种名为“仓库”的数据结构来保存

    2024年02月04日
    浏览(32)
  • OpenHarmony-4.0-Release 源码编译记录

    本文基于 Ubuntu 20.04.4 LTS 这个没啥好说的,都是搞机的,用之前编译 aosp 的 linux 环境就行,有小伙伴担心会把之前的环境搞崩, 也有用 docker 编译的,我这里就直接在 aosp 环境下搞了,还省事。 安装下面这三东西,是为了下载 Harmony 源码 sudo apt install curl sudo apt install python3

    2024年02月05日
    浏览(43)
  • spring-boot-2.2.13.RELEASE 升级 2.6.6 记录

    spring-boot-2.2.13.RELEASE 升级 2.6.6 旧依赖 新依赖 旧配置 新配置 在 bootstrap.properties 中新增如下配置 略

    2024年02月16日
    浏览(29)
  • 2022-07-15 Unity核心10——导航寻路系统

    ​ Unity 中的导航寻路系统是能够让我们在游戏世界当中,让角色能够从一个起点准确的到达另一个终点,并且能够自动避开两个点之间的障碍物选择最近最合理的路径进行前往 ​ Unity 中的导航寻路系统的本质,就是在 A 星寻路算法的基础上进行了拓展和优化 导航网格(NavM

    2023年04月08日
    浏览(35)
  • Kotlin学习记录

    除了java的 public , protected , default , private 外,又有独特的 internal , open 修饰符。 直译为内部的,访问范围是当前模块可见。使用示例: 默认情况下 class 和成员都是具备 final 修饰符的,即无法被继承和复写。 如果可以被继承或复写,需要添加 open 修饰。使用示例: 更多

    2024年02月09日
    浏览(28)
  • 深度学习15-讨论通用的Web导航和浏览器自动化的实际应用。

    ### Web导航 ▪  讨论通用的Web导航和浏览器自动化的实际应用。 ▪  探索如何通过RL方法解决Web导航问题。 ▪  深入研究由OpenAI实现的一个非常有趣但常被忽略且被抛弃的RL基准,称为比特迷你世界(Mini World of Bits,MiniWoB)。 RL浏览器自动化的潜在实际应用很有吸引力,但有

    2024年02月02日
    浏览(35)
  • Kotlin开发Android之基础问题记录

    1、Kotlin中如何直接通过组件id来操作组件? 解决方案:在build.gradle中添加对相应插件的使用即可。 2、Kotlin中Button设置背景颜色没有效果。 解决方案:在res-values-themes.xml文件中修改如下代码: 3、Kotlin中如何使用静态类或者静态方法? 解决方案: 4、Kotlin中EditText的赋值问题

    2024年02月09日
    浏览(31)
  • 【YOLO问题记录】UserWarning: torch.meshgrid: in an upcoming release,it will be required to pass the......

    在pycharm上训练yolo数据集的时候,运行train.py报错: 解决方法: 找到pyrcharm所用的虚拟环境下的functional.py文件,根据报错的提示找到functional的504行 加上代码indexing = \\\'ij\\\' 虽然这 好像是torch包里的源码, 按道理说不应该改,但是确实问题解决了 参考文章:YOLO UserWarning: torch.m

    2024年02月05日
    浏览(32)
  • 【采坑记录】kotlin compiler embeddable 下载超级慢

    今天碰到一个奇怪的问题:在家里用自己的电脑更新下公司的项目,突然发现重新构建工程时一直在跑下载kotlin compiler embeddable 的task,期间打了两把王者农药还没跑完就离谱,于是尝试了如下方案。 尝试方案1:gradle配置阿里云仓库 当时我是这样想的:kotlin compiler embeddable这

    2024年02月13日
    浏览(27)
  • git :合并某个分支上某次commit记录到另外一个分支

    需要将A分支的某次提交记录 ,合并到B分支 1)切回到 A分支 找到提交的commit id 可以使用git log 命令 或者 右键上次提交的记录 copy reversion number         git checkout A git log 2)  切回到 B分支  使用 git cherry-pick  A的 commitID ,回车 3)最后git status /git push 如果遇到问题,可以使

    2024年02月16日
    浏览(48)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包