简体   繁体   中英

HTML5 Device Orientation - reliable compass implementation?

I am working on a mobile web project that needs to know the compass direction the user's device is pointing. It's incredibly simple right now, but here's what I have:

        var updateDirection = function (evt) {
            $("#direction").val(evt.alpha);
        };

        window.addEventListener("deviceorientation", updateDirection);

Based on what I've researched so far, the alpha channel of the event should be the compass position. However, I've observed (and read) that there are a wide variety of implementations based on OS and browser.

  • On my HTC smartphone, in Chrome or the default Android browser, I only get a reasonable reading (0 degrees = North, 90 = East, so on) when I hold the phone perfectly vertical in a "selfie" position. Any angle to the phone throws readings quite far off.
  • On my Surface Pro using Chrome, I can't get a reading greater than about 50.
  • On my Surface Pro using Edge, I get very reasonable readings, but only when I hold the device horizontal, as if it was laying on a table.

It seems likely that people have achieved getting the compass direction in a mobile browser regardless of device. Is there some library I can use to do this? Or is it necessary to simply code for many different specific scenarios , like this example, which also didn't work for all the devices listed:

Device Orientation Events

Is that really necessary for you to use javascript to find out orientation?

You could possibly achieve the same result with CSS media queries

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