my.onCompassChange to receive compass heading data.
Parameters
Code Example
Basic Usage
Navigation App
Combining with Location
Related APIs
my.onCompassChange
Listen for compass data
my.offCompassChange
Stop listening
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Start listening for compass heading data.
my.onCompassChange to receive compass heading data.
| Property | Type | Required | Description |
|---|---|---|---|
| interval | String | No | Execution frequency of the callback functions that monitor compass data updates (the listeners registered with my.onCompassChange). Valid values: game (~20ms), ui (~60ms), normal (~200ms). Default: normal |
| success | Function | No | Callback on success |
| fail | Function | No | Callback on failure |
| complete | Function | No | Callback that always executes |
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);
}
});
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 });
}
});
fail callback to provide a fallback experience.