aretherecookies-mobile/js/apis/PositionApi.js
2020-04-03 21:21:00 -05:00

78 lines
2 KiB
JavaScript

// @flow
import { emitter } from '../streams/LocationStream';
import { getCoordsFromZip } from './GoogleMapsApi';
import { PermissionsAndroid, Platform } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Geolocation from 'react-native-geolocation-service';
const {
PERMISSIONS: { ACCESS_FINE_LOCATION },
RESULTS,
request: requestPermission,
} = PermissionsAndroid;
let locationPermissionResponse = false;
const askLocationPermission = async () => {
if (Platform.OS === 'ios') {
locationPermissionResponse = RESULTS.GRANTED;
} else if (locationPermissionResponse !== RESULTS.GRANTED) {
locationPermissionResponse = await requestPermission(ACCESS_FINE_LOCATION, {
title: "Where's the TP? Location Permission",
message: "Where's the TP? would like to use your location to find some cookies. Is that OK?",
});
}
return locationPermissionResponse === RESULTS.GRANTED;
};
export const getCurrentPosition = () => {
return new Promise((resolve, reject) => {
askLocationPermission().then((granted) => {
if (!granted) {
return reject('Permission was not given for location');
}
Geolocation.getCurrentPosition(
(pos: Position) => {
emitter(pos), resolve(pos);
return pos;
},
(err) => {
reject(err);
},
{
enableHighAccuracy: true,
timeout: 5000,
}
);
});
});
};
export const getPositionFromZip = async (zip: string) => {
const { lat: latitude, lng: longitude } = await getCoordsFromZip(zip);
const pos: any = {
coords: {
latitude,
longitude,
},
};
emitter(pos);
return pos;
};
export const getLocation: () => Promise<Position> = async () => {
const currentZip = await AsyncStorage.getItem('zipcode');
if (currentZip && currentZip !== 'usegps') {
return getPositionFromZip(currentZip);
} else {
AsyncStorage.setItem('zipcode', 'usegps');
return getCurrentPosition().catch((error) => {
AsyncStorage.removeItem('zipcode');
throw error;
});
}
};