CodeBlanks Logo Icon CodeBlanks

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.

Practice 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 }.

Starter code

App.js
import * as Location from 'expo-location';

export async function getLocation() {
  // get the current location and return lat/lng
}

Sample solution

App.js
const loc = await Location.getCurrentPositionAsync({
  accuracy: Location.Accuracy.High,
});
return { latitude: loc.coords.latitude, longitude: loc.coords.longitude };

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the location variable

Question
const ____ = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });
Answer
const loc = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.High });

Explanation: The loc variable carries the location object.

2 What does coords.latitude carry?

App.js
const lat = loc.???
  • lat
  • coords.latitude Correct answer
  • lng
  • latitude

Explanation: coords.latitude carries the latitude value.

3 Match each field to its meaning

Term Meaning
coords Location object
latitude Latitude
longitude Longitude
accuracy Accuracy

All lessons in Advanced