tezvyn:

Getting a one-time GPS location

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

One-shot location retrieval.

OUTLINE

ensure permission, then call a getCurrentPosition wrapped in a promise (or Expo Location.getCurrentPositionAsync) with await inside try/catch, reading coords.latitude and longitude.

WHAT THIS TESTS Whether you can retrieve a single location fix with proper async handling, including the prerequisite permission and the failure cases.

A GOOD ANSWER COVERS You first confirm location permission is granted, since a fix request without it fails or returns nothing. For the library, in an Expo app you use expo-location's Location.getCurrentPositionAsync, which already returns a promise, so you simply await it. In a bare app the common choice is react-native-geolocation-service or the community geolocation module, whose getCurrentPosition takes success and error callbacks; you wrap it in a new Promise so you can await it. You pass options such as desired accuracy and a timeout. You read the result from position.coords, specifically latitude and longitude. The whole call sits in a try/catch so timeouts, location-services-off, or denied permission surface as caught errors rather than unhandled rejections. You also distinguish a one-time getCurrentPosition from watchPosition, which subscribes to continuous updates and must be cleared.

COMMON WRONG ANSWERS Forgetting to request or verify permission first. Using watchPosition and never unsubscribing when only one reading is needed. Ignoring the error callback so a timeout becomes an unhandled rejection. Not setting a timeout, so the await can hang on a cold GPS. Reading latitude off the position object directly instead of position.coords.

LIKELY FOLLOW-UPS How do you tune accuracy versus battery and speed, why might the first fix be slow, how do you handle the location-services-disabled case, and how does this differ from continuous tracking.

ONE CONCRETE EXAMPLE With Expo: after ensuring permission, try { const pos = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High }); const { latitude, longitude } = pos.coords; } catch (e) { handle the timeout or disabled-services error }. With the callback API you would write a helper that returns new Promise((resolve, reject) => Geolocation.getCurrentPosition(resolve, reject, options)) and await that helper the same way.

Read the original → github.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.