0Pricing
React Native Academy · 강의

expo-location으로 GPS 위치 읽기

포그라운드 위치 권한을 요청하고 getCurrentPositionAsync로 현재 좌표를 가져온 다음 화면에 위도와 경도를 표시합니다.

expo-location으로 GPS 위치 읽기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What Is expo-location?

expo-location provides an API to read the device's geographic position using GPS, Wi-Fi triangulation, and cell tower data. It works on both iOS and Android without writing native code. You can get a one-time position fix, watch the location as the user moves, or geocode an address to coordinates and vice versa.

Installing expo-location

Use the Expo install command to get the SDK-compatible version of expo-location. In managed Expo projects, the native module is linked automatically. For bare React Native projects, you must also run pod install on iOS and update AndroidManifest.xml with the location permission declarations.

npx expo install expo-location

Requesting Foreground Location Permission

Location access requires explicit user permission. Call Location.requestForegroundPermissionsAsync() to ask for permission to read location while the app is in the foreground. Check the status field of the returned object — only proceed if it equals 'granted'. The hook version Location.useForegroundPermissions() simplifies this in functional components.

import * as Location from 'expo-location';

const [permission, requestPermission] = Location.useForegroundPermissions();

if (!permission) return <ActivityIndicator />;

if (!permission.granted) {
  return (
    <View>
      <Text>Location access is needed to show your position.</Text>
      <Button title='Allow Location' onPress={requestPermission} />
    </View>
  );
}

Getting the Current Position Once

Location.getCurrentPositionAsync() performs a single GPS fix and returns a LocationObject containing coords.latitude, coords.longitude, coords.accuracy (in meters), and a timestamp. Use this for one-time lookups like 'find nearby restaurants' where you do not need continuous tracking.

const [location, setLocation] = React.useState(null);

async function fetchLocation() {
  const loc = await Location.getCurrentPositionAsync({
    accuracy: Location.Accuracy.Balanced,
  });
  setLocation(loc);
  console.log('Lat:', loc.coords.latitude);
  console.log('Lng:', loc.coords.longitude);
  console.log('Accuracy:', loc.coords.accuracy, 'meters');
}

Accuracy Levels

expo-location provides several accuracy presets via Location.Accuracy. Use Lowest or Low for coarse location with minimal battery impact, Balanced for general use, and High or BestForNavigation when you need precise GPS coordinates for turn-by-turn navigation. Higher accuracy drains battery faster, so choose appropriately for your use case.

// Coarse — fast, low battery, uses Wi-Fi/cell
Location.Accuracy.Lowest      // ~3 km
Location.Accuracy.Low         // ~1 km
Location.Accuracy.Balanced    // ~100 m — good default

// Precise — uses GPS, more battery
Location.Accuracy.High        // ~10 m
Location.Accuracy.Highest     // ~1 m
Location.Accuracy.BestForNavigation // highest + sensors

Watching the Location Continuously

Location.watchPositionAsync starts a subscription that calls a callback every time the device's position changes by a specified distance or time interval. It returns a subscription object with a remove() method. Always call remove() in a useEffect cleanup function to stop tracking when the component unmounts and save battery.

useEffect(() => {
  let subscription: Location.LocationSubscription;

  async function startWatching() {
    subscription = await Location.watchPositionAsync(
      {
        accuracy: Location.Accuracy.High,
        distanceInterval: 10, // update every 10 meters
        timeInterval: 5000,   // or every 5 seconds
      },
      (loc) => setLocation(loc)
    );
  }

  startWatching();
  return () => subscription?.remove(); // cleanup on unmount
}, []);

Displaying Coordinates on Screen

Once you have a location object, display the coordinates in a human-readable format. Round latitude and longitude to 5-6 decimal places for readability — that corresponds to roughly 1-meter precision. Display the accuracy value so users understand how precise the reading is, especially on devices that cannot get a good GPS fix indoors.

export default function LocationDisplay() {
  const [location, setLocation] = React.useState(null);
  // ... permission check and fetch ...

  if (!location) return <Button title='Get Location' onPress={fetchLocation} />;

  return (
    <View>
      <Text>Latitude: {location.coords.latitude.toFixed(6)}</Text>
      <Text>Longitude: {location.coords.longitude.toFixed(6)}</Text>
      <Text>Accuracy: {location.coords.accuracy?.toFixed(0)} m</Text>
    </View>
  );
}

Reverse Geocoding: Coordinates to Address

Location.reverseGeocodeAsync converts latitude and longitude coordinates into a human-readable address. It returns an array of LocationGeocodedAddress objects with fields like street, city, region, country, and postalCode. Use the first result — it is the most likely match for the given coordinates.

async function getAddress(latitude: number, longitude: number) {
  const results = await Location.reverseGeocodeAsync({ latitude, longitude });
  if (results.length > 0) {
    const addr = results[0];
    return [addr.street, addr.city, addr.region, addr.country]
      .filter(Boolean)
      .join(', ');
  }
  return 'Unknown location';
}

Forward Geocoding: Address to Coordinates

Location.geocodeAsync converts a text address into latitude and longitude. This is useful for features like 'search nearby' where users type a location name. The function returns an array of results (multiple matches are possible for ambiguous addresses) each containing latitude, longitude, and altitude.

async function searchAddress(address: string) {
  const results = await Location.geocodeAsync(address);
  if (results.length > 0) {
    const { latitude, longitude } = results[0];
    console.log('Coordinates:', latitude, longitude);
    return { latitude, longitude };
  }
  return null;
}

Handling Location Errors

Location requests can fail when the user is indoors, when the device's GPS is disabled, or on simulators that do not have a simulated location set. Wrap location calls in try-catch and show a fallback UI. Check Location.hasServicesEnabledAsync() before requesting a position to detect when the device's location services are turned off in system settings.

async function fetchLocationSafe() {
  const enabled = await Location.hasServicesEnabledAsync();
  if (!enabled) {
    Alert.alert('Location Off', 'Please enable Location Services in Settings.');
    return;
  }
  try {
    const loc = await Location.getCurrentPositionAsync({
      accuracy: Location.Accuracy.Balanced,
    });
    setLocation(loc);
  } catch (err) {
    Alert.alert('Error', 'Could not get your location. Please try again.');
  }
}

Background Location Tracking

Tracking location when the app is in the background requires background location permission (requestBackgroundPermissionsAsync) and a background task defined with expo-task-manager. This is only needed for apps like fitness trackers or delivery apps. Apple and Google have strict review requirements for apps that use background location, so only request it if the feature is core to your app.

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: requestForegroundPermissionsAsync must be called and granted before any location reading is possible, getCurrentPositionAsync performs a one-time position fix while watchPositionAsync tracks continuous movement, and reverseGeocodeAsync converts coordinates to a human-readable address. Next up we explore scheduling local notifications.

자주 묻는 질문

“expo-location으로 GPS 위치 읽기” 강의는 무료인가요?

네 — “expo-location으로 GPS 위치 읽기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“expo-location으로 GPS 위치 읽기”에서 뭘 배우나요?

포그라운드 위치 권한을 요청하고 getCurrentPositionAsync로 현재 좌표를 가져온 다음 화면에 위도와 경도를 표시합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“expo-location으로 GPS 위치 읽기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. expo-camera로 카메라 접근하기
  2. expo-location으로 GPS 위치 읽기
  3. 로컬 알림 예약하기
  4. 권한을 적절하게 처리하기
← React Native Academy(으)로 돌아가기