5

Is it somehow possible to calculate the device speed in km/h using devicemotion/deviceorientation HTML5 API?

I would like to know if a user is walking/running/not moving and I can't use geolocation API as it has to work inside buildings as well.

Scdev
  • 373
  • 2
  • 13

1 Answers1

5

sure you can. the accerleration you get from the devicemotion event is in 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);

should do it. but I would take care because the accelerometer in the phones is not sooooo accurate ;)

Pascal Z.
  • 111
  • 2
  • 4