1 | import '../../utils/index.js';
|
2 | import { CallbackManager, MethodHandler } from '../../utils/handler.js';
|
3 | import { getDeviceInfo } from '../base/system.js';
|
4 | import { throttle } from '../../utils/lodash.js';
|
5 |
|
6 | const callbackManager = new CallbackManager();
|
7 | let compassListener;
|
8 |
|
9 |
|
10 |
|
11 | const deviceorientationEventName = ['absolutedeviceorientation', 'deviceorientationabsolute', 'deviceorientation'].find(item => {
|
12 | if ('on' + item in window) {
|
13 | return item;
|
14 | }
|
15 | }) || '';
|
16 |
|
17 |
|
18 |
|
19 | const 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 | };
|
29 | let CompassChangeTrigger = false;
|
30 |
|
31 |
|
32 |
|
33 | const 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 |
|
49 |
|
50 |
|
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 |
|
71 |
|
72 | const onCompassChange = callback => {
|
73 | callbackManager.add(callback);
|
74 | };
|
75 |
|
76 |
|
77 |
|
78 | const offCompassChange = callback => {
|
79 | callbackManager.remove(callback);
|
80 | };
|
81 |
|
82 | export { offCompassChange, onCompassChange, startCompass, stopCompass };
|
83 |
|