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

时间:2015-11-12 14:10:37

标签: javascript html5 devicemotion

是否可以使用devicemotion / deviceorientation HTML5 API以km / h计算设备速度?

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

1 个答案:

答案 0 :(得分:3)

确定你可以。您从devicemotion事件中获得的加速度为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);

应该这样做。但我会小心,因为手机中的加速度计并不太准确;)