Skip to content

Instantly share code, notes, and snippets.

@billpull
Last active January 26, 2023 00:34
Show Gist options
  • Save billpull/8bc6e49872cfee29aa5cef193b59c835 to your computer and use it in GitHub Desktop.
Save billpull/8bc6e49872cfee29aa5cef193b59c835 to your computer and use it in GitHub Desktop.
Capacitor Use Watch Position w/ Fallback to Get Current Position
const PositionProvider: React.FC = ({ children }) => {
const position = useCurrentPosition();
return (
<WatchLocationContext.Provider value={position}>
{children}
</WatchLocationContext.Provider>
);
};
const [showLocationHelp, setShowLocationHelp] = useState(false);
const currentLocation = useContext(WatchLocationContext);
const onSubmit = () => {
if (currentLocation.error) {
setShowLocationHelp(true);
return;
}
const {
currentPosition: { coords },
} = currentLocation;
// continue on
};
if (showLocationHelp) {
return <>Enable Your Location Prompt</>;
}
return <>Form</>;
const useCurrentPosition = (): GeoWatchPositionResult => {
const [position, setPosition] = useState<Position>();
const [watchId, setWatchId] = useState("");
const [error, setError] = useState();
const clearWatch = () => {
if (watchId) {
clearPosition({ id: watchId });
setWatchId("");
}
};
const startWatch = async () => {
if (!watchId) {
const id = await watchPosition(async (pos: Position | null, err) => {
if (err) {
setError(err);
}
if (pos) {
setPosition(pos);
} else {
const newPosition = await getCurrentPosition();
setPosition(newPosition);
}
});
setWatchId(id);
}
};
useEffect(() => {
startWatch();
return () => clearWatch();
}, []);
return { currentPosition: position, error };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment