React Native
getCurrentPositionAsync
Learn the current location with getCurrentPositionAsync.
getCurrentPositionAsync
To get the current location once you call Location.getCurrentPositionAsync. The function returns an object; the coords field carries the location info. coords.latitude is the latitude and coords.longitude is the longitude value.
The function takes an options object; for example { accuracy: Location.Accuracy.High } requests high accuracy. With high accuracy the location is more precise but slower to arrive. Example: const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High }). The result is read with loc.coords.latitude and loc.coords.longitude.
The coords field
The coords field of the location object is the most important part. coords.latitude carries the latitude value (for example 41.0082) and coords.longitude carries the longitude value (for example 28.9784). Together these two values define a point; it can be shown on a map.
coords also carries extra info like altitude (height), accuracy (accuracy radius), speed (speed). The most used are latitude and longitude. You write these values to state and show them as a marker on the map. Since the values are decimals they are processed as numbers.
Exercise Get the current location
Complete the getLocation function. Call const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High }). Return an object with return { latitude: loc.coords.latitude, longitude: loc.coords.longitude }.
Show example solution
const loc = await Location.getCurrentPositionAsync({
accuracy: Location.Accuracy.High,
});
return { latitude: loc.coords.latitude, longitude: loc.coords.longitude };
Test yourself
-
Write the location variable
const ____ = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
Show answer
const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
-
What does coords.latitude carry?
const lat = loc.???
- lat
- coords.latitude
- lng
- latitude
Show answer
coords.latitude — coords.latitude carries the latitude value.
-
Match each field to its meaning
- coords
- Location object
- latitude
- Latitude
- longitude
- Longitude
- accuracy
- Accuracy
Next lesson: watchPositionAsync