mirror of
https://gitlab.com/wheres-the-tp/ui-mobile.git
synced 2026-01-25 06:04:55 -06:00
78 lines
2 KiB
JavaScript
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: "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;
|
|
});
|
|
}
|
|
};
|