Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // todo:@flow
- import { AsyncStorage, Platform } from 'react-native';
- import * as Debug from 'App/src/Debug';
- import { toStringify } from 'App/src/utils/Utils';
- import { addPrefix } from 'App/src/utils/AsyncStorage';
- const location_key = addPrefix('location_enabled')
- export const ENABLE_LOCATION = true;
- export const DISABLE_LOCATION = false;
- let enableLocation:boolean = DISABLE_LOCATION;
- let position:any = {};
- let watchInterval: any;
- export const getEnableLocation = () => {
- return enableLocation;
- };
- const locationOptions = {
- enableHighAccuracy: true,
- timeout: 5000, // 5 sec
- maximumAge: 30*60*1000, // Upto 30 minutes
- distanceFilter: 100, // meters
- };
- export async function init() {
- Debug.logFn(() => `Location.init()...`);
- try {
- const enabled = await AsyncStorage.getItem(location_key);
- if (enabled === 'true') {
- enableLocation = ENABLE_LOCATION
- startLocationUpdates()
- }
- }
- catch (err) {
- Debug.logError(`Location.init(): error ${toStringify(err)}`);
- }
- Debug.logFn(() => `Location.init(): ...enableLocation ${enableLocation.toString()}`);
- }
- const startLocationUpdates = () => {
- if (Platform.OS === 'ios') {
- navigator.geolocation.requestAuthorization();
- }
- watchInterval = () => {
- navigator.geolocation.getCurrentPosition(onLocationSuccess, onLocationError, locationOptions);
- setInterval(watchInterval, 1800 * 1000)
- }
- watchInterval()
- Debug.logFn(() => `Watching position`);
- }
- export const setEnableLocation = (locOnOff:boolean) => {
- Debug.logFn(() => `setEnableLocation(): ${locOnOff.toString()}`);
- if (locOnOff && !enableLocation) {
- startLocationUpdates()
- }
- if (!locOnOff && enableLocation) {
- Debug.logFn(() => `Clearing location watch`);
- clearInterval(watchInterval);
- }
- enableLocation = locOnOff;
- AsyncStorage.setItem(location_key, locOnOff.toString())
- };
- export const getLastLocation = () => {
- return position;
- };
- export const getLocationData = () => {
- let data;
- if (getEnableLocation()) {
- const pos:any = getLastLocation();
- if (pos && pos.coords) {
- data = {
- last_known_location: {
- lat: pos.coords.latitude,
- lon: pos.coords.longitude,
- accuracy_meters: pos.coords.accuracy,
- timestamp_seconds: pos.timestamp/1000.0,
- }
- };
- }
- }
- return data;
- };
- const onLocationSuccess = (pos:any) => {
- Debug.logFn(() => `Got location update: ${JSON.stringify(pos)}`);
- position = pos;
- };
- const onLocationError = (err:any) => {
- Debug.logFn(() => `onLocationError: ${JSON.stringify(err)}`);
- if (enableLocation && err.PERMISSION_DENIED === 1) {
- startLocationUpdates()
- }
- Debug.logError(`Location request failed`, err);
- };
Add Comment
Please, Sign In to add comment