Get compass access from a web application using Javascript

Is it possible to access the compass with Javascript on the iphone / android device from a web application? I watched the network for hours, I know that you can access the accelerometer with

window.ondevicemotion = function (event)

Does anyone know if you can access information from a compass?

+3
source share
2 answers

On iPhone, you can get the compass value as follows.

window.addEventListener('deviceorientation', function(e) {
    console.log(e.webkitCompassHeading);
}, false);

I hope for this help.

+4
source

Now it looks like a cross platform, check out the excellent article by Ruadhan O'Donoghue .

Android - window.addEventListener('deviceorientation', ...), (event.alpha, , beta gamma , ).

(), :

   if(window.DeviceOrientationEvent) {
      window.addEventListener('deviceorientation', function(event) {
        var alpha;
        // Check for iOS property
        if(event.webkitCompassHeading) {
          alpha = event.webkitCompassHeading;
        }
        // non iOS
        else {
          alpha = event.alpha;
          if(!window.chrome) {
            // Assume Android stock
            alpha = alpha-270;
          }
        }
      }
    }

CodePen.

0

All Articles