UNPKG

@goongmaps/goong-map-react-native

Version:

A Goong GL react native module for creating custom maps

96 lines (76 loc) 2.12 kB
import {NativeModules, NativeEventEmitter} from 'react-native'; const GoongSDK = NativeModules.MGLModule; const GoongSDKLocationManager = NativeModules.MGLLocationModule; export const LocationModuleEventEmitter = new NativeEventEmitter( GoongSDKLocationManager, ); class LocationManager { constructor() { this._listeners = []; this._lastKnownLocation = null; this._isListening = false; this._isPaused = false; this.onUpdate = this.onUpdate.bind(this); } async getLastKnownLocation() { if (!this._lastKnownLocation) { const lastKnownLocation = await GoongSDKLocationManager.getLastKnownLocation(); if (!this._lastKnownLocation && lastKnownLocation) { this._lastKnownLocation = lastKnownLocation; } } return this._lastKnownLocation; } addListener(listener) { if (!this._listeners.includes(listener)) { this._listeners.push(listener); if (this._lastKnownLocation) { listener(this._lastKnownLocation); } } } removeListener(listener) { this._listeners = this._listeners.filter(l => l !== listener); } removeAllListeners() { this._listeners = []; } start() { if (this._isPaused) { GoongSDKLocationManager.start(); this._isPaused = false; return; } if (!this._isListening) { GoongSDKLocationManager.start(); LocationModuleEventEmitter.addListener( GoongSDK.LocationCallbackName.Update, this.onUpdate, ); this._isListening = true; } } pause() { if (!this._isPaused && this._isListening) { GoongSDKLocationManager.pause(); this._isListening = false; } } dispose() { GoongSDKLocationManager.stop(); if (this._isListening) { LocationModuleEventEmitter.removeListener( GoongSDK.LocationCallbackName.Update, this.onUpdate, ); } this._isListening = false; } onUpdate(location) { this._lastKnownLocation = location; for (const listener of this._listeners) { listener(location); } } } export default new LocationManager();