位置情報権限の取得場所を変更
This commit is contained in:
76
stateBox/useUserPosition.tsx
Normal file
76
stateBox/useUserPosition.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import React, {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
FC,
|
||||
} from "react";
|
||||
import {
|
||||
LocationObject,
|
||||
requestForegroundPermissionsAsync,
|
||||
getCurrentPositionAsync,
|
||||
} from "expo-location";
|
||||
import { Platform } from "react-native";
|
||||
import useInterval from "@/lib/useInterval";
|
||||
|
||||
type initialStateType = {
|
||||
position: LocationObject | undefined;
|
||||
getCurrentPosition: () => void;
|
||||
locationStatus: boolean | null;
|
||||
getLocationPermission: () => void;
|
||||
};
|
||||
const initialState = {
|
||||
position: undefined,
|
||||
getCurrentPosition: () => {},
|
||||
locationStatus: null,
|
||||
getLocationPermission: () => {},
|
||||
};
|
||||
|
||||
const UserPositionContext = createContext<initialStateType>(initialState);
|
||||
type Props = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
export const useUserPosition = () => {
|
||||
return useContext(UserPositionContext);
|
||||
};
|
||||
|
||||
export const UserPositionProvider: FC<Props> = ({ children }) => {
|
||||
//位置情報
|
||||
const [locationStatus, setLocationStatus] = useState<boolean | null>(null);
|
||||
const [position, setPosition] = useState<LocationObject | undefined>(
|
||||
undefined
|
||||
);
|
||||
|
||||
const getLocationPermission = async () => {
|
||||
return requestForegroundPermissionsAsync().then((data) => {
|
||||
setLocationStatus(
|
||||
Platform.OS == "ios"
|
||||
? data.status == "granted"
|
||||
: data.android.accuracy == "fine"
|
||||
);
|
||||
});
|
||||
};
|
||||
const getCurrentPosition = () => {
|
||||
if (!locationStatus) return () => {};
|
||||
getCurrentPositionAsync({}).then((location) => setPosition(location));
|
||||
};
|
||||
useEffect(() => {
|
||||
if (Platform.OS == "web") return;
|
||||
getLocationPermission();
|
||||
}, []);
|
||||
useEffect(getCurrentPosition, [locationStatus]);
|
||||
useInterval(getCurrentPosition, 5000);
|
||||
|
||||
return (
|
||||
<UserPositionContext.Provider
|
||||
value={{
|
||||
position,
|
||||
getCurrentPosition,
|
||||
locationStatus,
|
||||
getLocationPermission,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</UserPositionContext.Provider>
|
||||
);
|
||||
};
|
Reference in New Issue
Block a user