Mapbox SDK 9迁移至11后Android端Directions API返回body始终为null
Mapbox 11 Directions API
response.body() 始终返回null的解决思路 问题概述
在Mapbox 11中调用Directions API时,response.body()始终返回null,使用的是Mapbox 9项目中可正常工作的访问令牌,已按新API要求用RouteOptions替代旧的.origin/.destination方法,代码基于旧Java示例迁移为Kotlin。
可能的原因及修复方案
访问令牌获取错误
代码中accessToken(R.string.mapbox_access_token.toString())是错误写法:R.string.mapbox_access_token是资源ID,直接toString会得到一串数字而非实际令牌值。
修复:通过上下文获取字符串值,比如requireContext().getString(R.string.mapbox_access_token)。RouteOptions配置不匹配场景
applyDefaultNavigationOptions()是针对导航场景的默认配置,如果你只是获取普通路线而非导航路径,建议替换为applyDefaultRoutesOptions(),避免不必要的配置冲突。未排查API请求错误详情
只判断response.body()为空无法定位问题,需打印响应状态码和错误体,获取具体失败原因(如令牌权限不足、请求格式错误等)。
示例代码:override fun onResponse(call: Call<DirectionsResponse?>, response: Response<DirectionsResponse?>) { if (!response.isSuccessful) { val errorInfo = response.errorBody()?.string() ?: "无具体错误信息" Log.e("MapFragment", "请求失败,状态码:${response.code()},错误详情:$errorInfo") return } // 后续处理响应体逻辑 }依赖与权限检查
确保build.gradle中Mapbox依赖为11.x最新版本,同时AndroidManifest.xml中声明网络权限:<uses-permission android:name="android.permission.INTERNET" />
修复后的核心代码示例
private fun getInformationFromDirectionsApi( destinationPoint: Point, fromMarkerClick: Boolean, listIndex: Int? ) { val destinationMarker = Point.fromLngLat(destinationPoint.longitude(), destinationPoint.latitude()) val mockOriginLocation = Point.fromLngLat(120.59270718466132, 16.418361457286892) val routeOptions: RouteOptions = RouteOptions.builder() .applyDefaultRoutesOptions() .profile(DirectionsCriteria.PROFILE_WALKING) .coordinatesList(listOf(mockOriginLocation, destinationMarker)) .build() val directionsApiClient: MapboxDirections = MapboxDirections.builder() .routeOptions(routeOptions) .accessToken(requireContext().getString(R.string.mapbox_access_token)) .build() directionsApiClient.enqueueCall(object : Callback<DirectionsResponse?> { override fun onResponse(call: Call<DirectionsResponse?>, response: Response<DirectionsResponse?>) { if (!response.isSuccessful) { val errorMsg = response.errorBody()?.string() ?: "未知错误" Log.e("MapFragment", "API请求失败:状态码${response.code()},错误:$errorMsg") return } val body = response.body() when { body == null -> Log.e("MapFragment", "响应体为空") body.routes().isEmpty() -> Log.e("MapFragment", "未找到可用路线") else -> { // 处理路线数据逻辑 } } } override fun onFailure(call: Call<DirectionsResponse?>, t: Throwable) { Log.e("MapFragment", "请求发起失败", t) } }) }
内容的提问来源于stack exchange,提问作者ColstonBod-oy
相关产品推荐
相关产品推荐

