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

如何在Expo React Native中通过Expo Location获取车辆速度

如何在Expo React Native中追踪车辆速度

有两种方法可以实现车辆速度追踪,以下是具体实现方案:


方法一:直接读取Expo Location API返回的speed值

Expo Location的位置数据中自带speed字段,你可以直接在位置更新回调中获取该值,无需自行计算。注意这个值的单位是米/秒,如果需要转换成常用的公里/小时,乘以3.6即可;另外当设备静止或无法获取速度数据时,speed可能为null,需要做判空处理。

修改你的TaskManager回调代码如下:

TaskManager.defineTask(LOCATION_TRACKING, async ({ data, error }) => {
  if (error) {
    console.log('LOCATION_TRACKING task ERROR:', error);
    return;
  }
  if (data) {
    const { locations } = data;
    const currentCoords = locations[0].coords;
    const lat = currentCoords.latitude;
    const long = currentCoords.longitude;
    
    // 获取并处理速度值
    const speedMps = currentCoords.speed;
    let speedKmh = null;
    if (speedMps !== null) {
      speedKmh = speedMps * 3.6; // 转换为公里/小时
      console.log('当前速度(km/h):', speedKmh.toFixed(2));
    } else {
      console.log('无法获取速度数据');
    }

    // 建议用组件状态替代全局变量,避免副作用
    // setLat(lat);
    // setLong(long);
    // setOrigin(`${lat},${long}`);
  }
});

方法二:手动通过坐标变化计算速度

如果设备无法提供speed数据,或者你需要自定义计算逻辑,可以通过记录前后两次的位置坐标和时间戳,用Haversine公式计算两点间的直线距离,再除以时间差得到速度。

步骤1:保存历史位置和时间状态

在组件内添加状态来存储上一次的位置和时间戳:

import { useState } from 'react';
import * as Location from 'expo-location';

// 组件内部状态
const [prevCoords, setPrevCoords] = useState(null);
const [prevTimestamp, setPrevTimestamp] = useState(null);

步骤2:在回调中计算速度

修改TaskManager回调,加入速度计算逻辑:

TaskManager.defineTask(LOCATION_TRACKING, async ({ data, error }) => {
  if (error) {
    console.log('LOCATION_TRACKING task ERROR:', error);
    return;
  }
  if (data) {
    const { locations } = data;
    const currentCoords = locations[0].coords;
    const currentTime = locations[0].timestamp; // 时间戳(毫秒)

    // 有历史数据时计算速度
    if (prevCoords && prevTimestamp) {
      // Haversine公式计算两点距离(单位:米)
      const earthRadius = 6371000; // 地球半径(米)
      const lat1 = prevCoords.latitude;
      const lon1 = prevCoords.longitude;
      const lat2 = currentCoords.latitude;
      const lon2 = currentCoords.longitude;

      const dLat = (lat2 - lat1) * Math.PI / 180;
      const dLon = (lon2 - lon1) * Math.PI / 180;
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      const distance = earthRadius * c; // 两点距离(米)

      // 计算时间差(秒)并转换速度单位
      const timeDiff = (currentTime - prevTimestamp) / 1000;
      const speedKmh = (distance / timeDiff) * 3.6;

      console.log('计算得到的速度(km/h):', speedKmh.toFixed(2));
    }

    // 更新历史数据
    setPrevCoords(currentCoords);
    setPrevTimestamp(currentTime);

    // 处理当前坐标
    const lat = currentCoords.latitude;
    const long = currentCoords.longitude;
    // setLat(lat);
    // setLong(long);
    // setOrigin(`${lat},${long}`);
  }
});

注意事项

  • 手动计算的精度依赖于GPS精度和位置更新频率,你当前设置的5秒间隔可能导致速度数据不够平滑,可根据需求调整timeInterval或distanceInterval参数。
  • 当设备静止时,GPS漂移可能导致微小距离变化,可设置距离阈值(比如小于1米时判定为静止)来避免误差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:05:18