UNPKG

3.38 kBJavaScriptView Raw
1import '../../utils/index.js';
2import { CallbackManager, MethodHandler } from '../../utils/handler.js';
3import { getDeviceInfo } from '../base/system.js';
4import { throttle } from '../../utils/lodash.js';
5
6const callbackManager = new CallbackManager();
7let compassListener;
8/**
9 * Note: 按系统类型获取对应绝对 orientation 事件名,因为安卓系统中直接监听 deviceorientation 事件得到的不是绝对 orientation
10 */
11const deviceorientationEventName = ['absolutedeviceorientation', 'deviceorientationabsolute', 'deviceorientation'].find(item => {
12 if ('on' + item in window) {
13 return item;
14 }
15}) || '';
16/**
17 * 停止监听罗盘数据
18 */
19const stopCompass = ({ success, fail, complete } = {}) => {
20 const handle = new MethodHandler({ name: 'stopCompass', success, fail, complete });
21 try {
22 window.removeEventListener(deviceorientationEventName, compassListener, true);
23 return handle.success();
24 }
25 catch (e) {
26 return handle.fail({ errMsg: e.message });
27 }
28};
29let CompassChangeTrigger = false;
30/**
31 * 开始监听罗盘数据
32 */
33const startCompass = ({ success, fail, complete } = {}) => {
34 const handle = new MethodHandler({ name: 'startCompass', success, fail, complete });
35 try {
36 if (deviceorientationEventName !== '') {
37 if (compassListener) {
38 stopCompass();
39 }
40 compassListener = throttle((evt) => {
41 const isAndroid = getDeviceInfo().system === 'AndroidOS';
42 if (isAndroid && !evt.absolute && !CompassChangeTrigger) {
43 CompassChangeTrigger = true;
44 console.warn('Warning: In \'onCompassChange\', your browser is not supported to get the orientation relative to the earth, the orientation data will be related to the initial orientation of the device .');
45 }
46 const alpha = evt.alpha || 0;
47 /**
48 * 由于平台差异,accuracy 在 iOS/Android 的值不同。
49 * - iOS:accuracy 是一个 number 类型的值,表示相对于磁北极的偏差。0 表示设备指向磁北,90 表示指向东,180 表示指向南,依此类推。
50 * - Android:accuracy 是一个 string 类型的枚举值。
51 */
52 const accuracy = isAndroid ? evt.absolute ? 'high' : 'medium' : alpha;
53 callbackManager.trigger({
54 direction: 360 - alpha,
55 accuracy: accuracy
56 });
57 }, 5000);
58 window.addEventListener(deviceorientationEventName, compassListener, true);
59 }
60 else {
61 throw new Error('compass is not supported');
62 }
63 return handle.success();
64 }
65 catch (e) {
66 return handle.fail({ errMsg: e.message });
67 }
68};
69/**
70 * 监听罗盘数据变化事件。频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。
71 */
72const onCompassChange = callback => {
73 callbackManager.add(callback);
74};
75/**
76 * 取消监听罗盘数据变化事件,参数为空,则取消所有的事件监听。
77 */
78const offCompassChange = callback => {
79 callbackManager.remove(callback);
80};
81
82export { offCompassChange, onCompassChange, startCompass, stopCompass };
83//# sourceMappingURL=compass.js.map