简体   繁体   中英

absolute device orientation on mobile devices

I am trying to get the absolute device orientation across different mobile devices (android + IOs) and browsers in a more or less reliable way. I would rather be able to understand if the orientation I am receiving is relative and not show the compass instead of showing wrong values.
I have been googling back and forth for days and I haven't found a definitive answer yet (I am a javascript and web dev novice).
I see that the Full-Tilt library should be doing exactly that but it has a non commercial license. I intend to use this result in a potentially commercial project, moreover, I would like to understand what's happening.

Nowadays most deviceorientation events are returning relative values.
deviceorientationabsolute is not supported by firefox and it's an experimental feature, I can fallback on it when other things fail but it cannot be the main solution.

So far I've got to this line of reasoning (pseudocode):

if(mobile)
  if(webkitmobilecompassheading)
    window.addEventListener("deviceorientation", handleOrientationWebkit, true);
  else if(deviceorientationabsolute)
    window.addEventListener("deviceorientation", handleOrientationAbsolute, true);
  else
    "bad luck"   

I have no idea where to look to understand how many devices I would miss out on with the following reasoning, and if there is a better way.

For Android it works auto, for iOS it needs to be clicked to start it. Here's a part of code you can use for that

startBtn.addEventListener("click", startCompass);

function startCompass() {
  if (isIOS) {
    DeviceOrientationEvent.requestPermission()
      .then((response) => {
        if (response === "granted") {
          window.addEventListener("deviceorientation", handler, true);
        } else {
          alert("has to be allowed!");
        }
      })
      .catch(() => alert("not supported"));
  } else {
    window.addEventListener("deviceorientationabsolute", handler, true);
  }
}

function handler(e) {
  const degree = e.webkitCompassHeading || Math.abs(e.alpha - 360);
}

Full tutorial is here, try demo also https://dev.to/orkhanjafarovr/real-compass-on-mobile-browsers-with-javascript-3emi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM