7

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Drew Dara-Abrams
  • 8,016
  • 11
  • 40
  • 48
  • 1
    Just noticed this W3C Compass API draft published today: http://dev.w3.org/2009/dap/system-info/compass.html So maybe this sort of functionality will arrive somewhat. – Drew Dara-Abrams Apr 01 '10 at 23:23
  • In iOS5 you can access the compass with webkitCompassHeading check out [this documentation](https://developer.apple.com/library/safari/#documentation/SafariDOMAdditions/Reference/DeviceOrientationEventClassRef/DeviceOrientationEvent/DeviceOrientationEvent.html#//apple_ref/javascript/instp/DeviceOrientationEvent/webkitCompassHeading) –  Oct 13 '11 at 18:09

4 Answers4

4

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.

Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
3

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
christo16
  • 4,843
  • 5
  • 42
  • 53
  • 1
    this answer is no longer true, iOS 4.2 provides webkitCompassHeading, look at awoodland's answer – ianj Oct 25 '11 at 19:35
2

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

Orkhan Jafarov
  • 215
  • 2
  • 7
0

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/

stefcud
  • 2,220
  • 4
  • 27
  • 37