Parameters
Callback Parameters
Code Example
Basic Usage
Compass Display
Navigation Arrow
Related APIs
my.offCompassChange
Stop listening for changes
my.startCompass
Start compass
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Listen for compass heading changes.
| Property | Type | Required | Description |
|---|---|---|---|
| listener | Function | Yes | A callback that monitors compass data updates. When executed, it receives a res object containing updated compass data. |
| Property | Type | Description |
|---|---|---|
| direction | Number | The clockwise angle (in degrees) between the device’s orientation and true north. Valid range: [0, 360) |
| timestamp | Number | Timestamp when the compass data is recorded |
my.onCompassChange((res) => {
console.log('Direction:', res.direction);
});
Page({
data: {
direction: 0,
cardinalDirection: 'N'
},
onLoad() {
my.onCompassChange((res) => {
this.setData({
direction: Math.round(res.direction),
cardinalDirection: this.getCardinalDirection(res.direction)
});
});
},
getCardinalDirection(degrees) {
const directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
const index = Math.round(degrees / 45) % 8;
return directions[index];
},
onUnload() {
my.offCompassChange();
}
});
Page({
data: {
targetBearing: 45, // Target is NE
arrowRotation: 0
},
onLoad() {
my.onCompassChange((res) => {
// Calculate rotation to point at target
const rotation = this.data.targetBearing - res.direction;
this.setData({ arrowRotation: rotation });
});
}
});
my.startCompass before using this API to begin receiving compass data.