aretherecookies-mobile/js/apis/PositionApi.js
2019-09-21 15:45:07 +00:00

77 lines
1.9 KiB
JavaScript

// @flow
import { emitter } from "../streams/LocationStream";
import { getCoordsFromZip } from "./GoogleMapsApi";
import { AsyncStorage, PermissionsAndroid, Platform } from "react-native";
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: "Aretherecookies? Location Permission",
message: "Aretherecookies? 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;
});
}
};