Last active
January 26, 2023 00:34
-
-
Save billpull/8bc6e49872cfee29aa5cef193b59c835 to your computer and use it in GitHub Desktop.
Capacitor Use Watch Position w/ Fallback to Get Current Position
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const PositionProvider: React.FC = ({ children }) => { | |
const position = useCurrentPosition(); | |
return ( | |
<WatchLocationContext.Provider value={position}> | |
{children} | |
</WatchLocationContext.Provider> | |
); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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</>; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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