Scdev
Scdev

Reputation: 371

HTML5/Javascript calculate device speed using devicemotion/deviceorientation

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.

Upvotes: 5

Views: 2666

Answers (1)

Pascal Z.
Pascal Z.

Reputation: 121

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 ;)

Upvotes: 5

Related Questions