Getting device compass heading in a PWA?

My students and I are trying to build a little PWA app that requires showing which direction the user is facing – i.e., the compass heading.

We have been unable to find a solution that works reliably. The Cordova implementation of DeviceOrientation gives an error about “cordova_not_available”, and other things we’ve tried have given very poor compass direction results.

Has anyone out there in Ionicland solved this problem? If so, can you help?



You can use the response from the Geolocation API, the heading value

Try to use watchPosition() as the accuracy gets better if you let it track your device for a while

There is a capacitor version that supports PWA: Geolocation Capacitor Plugin API | Capacitor Documentation

Thanks. I tried this and got very poor results, at least on my phone… So, I was hoping for some others to say they’ve used it and it worked well for them. or to show me their code so i could see what I did wrong.

Can you show your example code of what you are doing? both cordova and capacitor geolocation plugins work fine. It may be that you have the code in the wrong lifecycle method.

Capacitor’s Motion plugin uses devicedrientation event

1 Like

In a projectI’m working on we managed to do that with cordova-plugin-device-orientation.

If you want to calculated yourself here is an example.
DeviceOrientation Event Specification (

I got this code to work:

    window.navigator.geolocation.watchPosition(position => {
          this.heading = position.coords.heading;
        error => {
          this.errorMsg = error.message;
          enableHighAccuracy: true,
        //   timeout: 5000,
        //   maximumAge: 0

I found that I had other code in my app that was listening on window’s deviceorientation and the computing the heading from alpha, beta, etc., and that seemed to really screw things up. When I commented that code out, the above code worked.

Thanks for everyone’s feedback.

when you got this to work, what kind of result did you see in the browser? (I’m getting ‘null’)

Do you get a reading even when the device is stationary? (I get a null heading when the device isn’t moving)