Skip to main content
Use this API to start the compass sensor. After calling this, you can use my.onCompassChange to receive compass heading data.

Parameters

PropertyTypeRequiredDescription
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback that always executes

Code Example

Basic Usage

my.startCompass({
  success() {
    console.log('Compass started');
    my.onCompassChange((res) => {
      console.log('Heading:', res.direction);
    });
  }
});
Page({
  onLoad() {
    my.startCompass({
      success: () => {
        my.onCompassChange(this.updateCompass);
      },
      fail(err) {
        my.showToast({
          content: 'Compass not available',
          type: 'fail'
        });
      }
    });
  },

  updateCompass(res) {
    this.setData({
      heading: Math.round(res.direction),
      compassRotation: -res.direction
    });
  },

  onUnload() {
    my.offCompassChange(this.updateCompass);
  }
});

Combining with Location

Page({
  async onLoad() {
    // Start compass for heading
    my.startCompass({
      success: () => {
        my.onCompassChange(this.updateHeading);
      }
    });

    // Get current location
    my.getLocation({
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      }
    });
  },

  updateHeading(res) {
    this.setData({ heading: res.direction });
  }
});
The compass may not be available on all devices. Always handle the fail callback to provide a fallback experience.

my.onCompassChange

Listen for compass data

my.offCompassChange

Stop listening