You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MapBox中Location.speed始终为0的技术求助

问题解决:LocationChangeListeningCallback中速度始终为0的问题

核心问题分析

你代码里的速度计算逻辑完全错误:

var location = Location(LocationManager.GPS_PROVIDER)
// ...
if(location.hasSpeed())
    speed = location.speed/18*5
else
    speed = 0F

这里你新建了一个空的Location对象,它没有任何实际的定位数据,所以hasSpeed()必然返回false,speed自然始终是0。你应该直接使用LocationEngineCallback回调返回的result.lastLocation——这才是包含当前定位信息(包括速度)的对象。

修正后的代码

把速度计算部分改成这样:

if(pointList.size>1) {
    val results = FloatArray(5)
    val lastlat = pointList[pointList.lastIndex - 1]
    var xLng = lastlat.coordinates()[0]
    var yLat = lastlat.coordinates()[1]
    Location.distanceBetween(yLat, xLng, lat, lng, results)

    // 直接使用回调返回的lastLocation获取速度
    val currentLocation = result.lastLocation!!
    if(currentLocation.hasSpeed()) {
        // speed单位是m/s,转成km/h的话是乘以3.6,你这里的/18*5其实也是3.6的近似值
        speed = currentLocation.speed * 3.6f
    } else {
        speed = 0F
    }
    accDistance += results[0]

    textViewDistance.text = "Distance in meters covered: $accDistance\nCurrent Velocity: $speed"
}

额外注意事项

  1. 定位权限与模式:

    • 确保已经动态申请了ACCESS_FINE_LOCATION权限(Android 6.0+必须动态申请,仅在Manifest里声明没用)
    • 检查你的enableLocationComponent方法是否配置了高精度定位模式,只有GPS或融合定位的高精度模式才会返回有效速度值。比如在配置LocationComponentOptions时,设置:
      val locationComponentOptions = LocationComponentOptions.builder(this)
          .trackingGesturesManagement(true)
          .accuracyColor(Color.RED)
          .build()
      val locationComponentActivationOptions = LocationComponentActivationOptions.builder(this, style)
          .locationComponentOptions(locationComponentOptions)
          .useDefaultLocationEngine(true)
          .build()
      map.locationComponent.activateLocationComponent(locationComponentActivationOptions)
      
    • 测试时尽量在户外开阔区域,室内GPS信号弱可能无法返回速度。
  2. 代码冗余优化:
    你在onSuccess回调里每次都调用map_view.getMapAsync并重新设置Style、添加图层,这会导致重复创建资源,建议把图层初始化逻辑移到onMapReady的Style设置回调里,后续只更新GeoJsonSource的数据即可:

    // 在onMapReady的style回调里初始化一次图层
    val geoJsonSource = GeoJsonSource("line-source")
    style.addSource(geoJsonSource)
    style.addLayer(
        LineLayer("linelayer", "line-source").withProperties(
            PropertyFactory.lineWidth(3f),
            PropertyFactory.lineColor(Color.parseColor("#FF0000"))
        )
    )
    // 后续在onSuccess里只更新数据
    geoJsonSource.setGeoJson(FeatureCollection.fromFeatures(
        arrayOf(Feature.fromGeometry(LineString.fromLngLats(pointList)))
    ))
    

内容的提问来源于stack exchange,提问作者Bernd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:51:56