Drew Dara-Abrams
Drew Dara-Abrams

Reputation: 8054

accessing iPhone compass with JavaScript

Know if it's possible to access the iPhone compass in Safari using JavaScript? I see how the GPS can be accessed, but I can't figure out the compass.

Upvotes: 7

Views: 8841

Answers (4)

stefcud
stefcud

Reputation: 2315

I advise you to use LeafletJS with this plugin
https://github.com/stefanocudini/leaflet-compass

very simple to use with events and methods.

You can try a demo here:
https://opengeo.tech/maps/leaflet-compass/

Upvotes: 0

Orkhan Jafarov
Orkhan Jafarov

Reputation: 255

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

Upvotes: 2

christo16
christo16

Reputation: 4843

You cannot access that information via javascript, unless you're using something like iPhoneGap

At the time this was true, in iOS 5 you can use the compass heading in JS. https://developer.apple.com/documentation/webkitjs/deviceorientationevent/1804777-webkitcompassheading

Upvotes: 3

Simon Arnold
Simon Arnold

Reputation: 16177

On iOS, you can retrieve the compass value like this.

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

For more informations, read the Apple DeviceOrientationEvent documentation.

Hope this helps.

Upvotes: 4

Related Questions