使用devicemotion/deviceorientation计算设备速度的HTML5/Javascript

5

是否有可能使用devicemotion/deviceorientation HTML5 API计算设备的速度(以公里/小时为单位)?

我想知道用户是在步行/跑步/静止不动,但我不能使用地理位置API,因为它也必须在建筑物内工作。

1个回答

5
当然可以。从设备运动事件中获取的加速度单位是m/s²。
var lastTimestamp;
var speedX = 0, speedY = 0, speedZ = 0;
window.addEventListener('devicemotion', function(event) {
  var currentTime = new Date().getTime();
  if (lastTimestamp === undefined) {
    lastTimestamp = new Date().getTime();
    return; //ignore first call, we need a reference time
  }
  //  m/s² / 1000 * (miliseconds - miliseconds)/1000 /3600 => km/h (if I didn't made a mistake)
  speedX += event.acceleration.x / 1000 * ((currentTime - lastTimestamp)/1000)/3600;
  //... same for Y and Z
  lastTimestamp = currentTime;
}, false);

应该可以这样做。但要注意,手机中的加速度计并不是非常准确;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接