Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 243
Scdev Avatar asked Nov 12 '15 14:11

Scdev


1 Answers

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

like image 62
Pascal Z. Avatar answered Sep 22 '22 20:09

Pascal Z.