강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

dev님의 프로필 이미지
dev

작성한 질문수

React Native with Expo: 제로초에게 제대로 배우기

expo-location으로 위치정보 다루기

Location.getCurrentPositionAsync({}); 에러

작성

·

30

0

npm ls react 19.1.0
npm ls react-native 0.81.5
npm ls expo 54.0.27


버전을 알려주시면 질문자분과 동일한 환경에서 답변 드릴 수 있습니다.

에뮬레이터에 location도 설정했는데 왜 마크표시를 누르면 아래 에러가 발생하는걸까요.. 빌드 지우고 다시 설치하고도 해봤습니다.

 LOG  getMyLocation granted
 ERROR  [Error: Uncaught (in promise, id: 1) Error: Current location is unavailable. Make sure that location services are enabled] 

Code: construct.js
  2 | var setPrototypeOf = require("./setPrototypeOf.js");
  3 | function _construct(t, e, r) {
> 4 |   if (isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
    |                                                                 ^
  5 |   var o = [null];
  6 |   o.push.apply(o, e);
  7 |   var p = new (t.bind.apply(t, o))();
Call Stack
  construct (<native>)
  apply (<native>)
  _construct (node_modules/@babel/runtime/helpers/construct.js:4:65)
  Wrapper (node_modules/@babel/runtime/helpers/wrapNativeSuper.js:15:23)
  construct (<native>)
  _callSuper (node_modules/@babel/runtime/helpers/callSuper.js:5:108)
  constructor (node_modules/expo-modules-core/src/errors/CodedError.ts:11:5)

 

답변 2

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

4번처럼 권한 요청 한 번 해보시겠어요? console.log(status)도 한 번 찍어보세요.

dev님의 프로필 이미지
dev
질문자

const getMyLocation = async (id: string) => {
      const servicesEnabled = await Location.hasServicesEnabledAsync();
      console.log("servicesEnabled", servicesEnabled);
      if (!servicesEnabled) {
          // GPS 서비스가 꺼져 있을 때 사용자에게 알림 및 설정 유도
          Alert.alert("GPS 꺼짐", "위치 서비스를 켜주세요.");
          return;
      }

      let { status } = await Location.requestForegroundPermissionsAsync();
      console.log('getMyLocation', status);
      if (status !== 'granted') {
          Alert.alert("위치권한 에러", "위치 권한을 허용해주세요.",[
              {
                  text: "Open settings",
                  onPress: () => {
                      Linking.openSettings()
                  }
              },
              {
                  text: "Cancel"
              }
          ])
          return;
      }

      try {
        let location = await Location.getCurrentPositionAsync({
          accuracy: Location.Accuracy.Balanced,
        });
        // Use the location data here
        console.log('Location success:', location);
        setThreads((prevThreads) => 
          prevThreads.map((threads) =>
              threads.id === id ? { ...threads, location: [location.coords.latitude, location.coords.longitude]  } : threads
          )
        );

      } catch(error) {
        console.log('Location error:', error);
      }

    };

이렇게 실행했을 때 로그가 아래와 같습니다ㅠ 권한 설정은 제대로 된것 같은데 gps값만 못가져오는것같습니다..

 LOG  servicesEnabled true
 LOG  getMyLocation granted
 LOG  Location error: [Error: Current location is unavailable. Make sure that location services are enabled]

 

 

dev님의 프로필 이미지
dev
질문자

혹시나 해서 구글맵 > 현재 내 위치 버튼 클릭 -> 정상작동 확인 -> 다시 expo로 이동 후 확인 > 정상 작동
코드와 빌드를 재실행 한건 없는데 위와 같이 한번 해보니까 갑자기 정상 실행되네요.. 답변 감사합니다 ㅠ

0

안녕하세요, 인프런 AI 인턴입니다. dev님.

Expo의 Location.getCurrentPositionAsync() 메서드를 사용할 때 “Current location is unavailable” 에러를 받으셨군요. 이는 일반적으로 권한 문제 또는 위치 서비스가 비활성화된 경우, 혹은 시뮬레이터에서 위치 설정이 제대로 되지 않은 경우 발생할 수 있습니다.

여기 몇 가지 해결 방법을 제시해드립니다:

  1. 위치 권한 확인: 앱이 위치 서비스에 대한 올바른 권한을 가지고 있는지 확인하세요. Expo 프로젝트에서는 Permissions.getAsync(Permissions.LOCATION)을 사용하여 위치 권한 상태를 확인할 수 있습니다.

  2. 에뮬레이터 위치 설정: 에뮬레이터의 위치 설정이 올바르게 되어있는지 확인해야 합니다. iOS의 경우, 시뮬레이터에서 디버그 > 위치 > 커스텀 위치 설정, Android의 경우 에뮬레이터 설정에서 GPS가 활성화된지 확인하세요.

  3. 위치 서비스 활성화: 실제 기기 사용 시, 장치의 설정에서 위치 서비스가 활성화되어 있는지 확인하세요.

  4. 권한 요청: 권한을 수동으로 요청해야 할 수도 있습니다. Location.requestForegroundPermissionsAsync()를 사용하여 위치 서비스에 대한 권한을 명시적으로 요청해보세요.

   const { status } = await Location.requestForegroundPermissionsAsync();
   if (status !== 'granted') {
     console.log('Permission not granted!');
     return;
   }
   const location = await Location.getCurrentPositionAsync({});
  1. 환경 체크: Expo와 React Native의 버전 호환성 문제가 있을 수 있으므로, 최신 안정 버전을 사용하고 있는지 확인해보세요.

아래 링크에서 비슷한 문제와 해결 방법에 대한 유용한 정보를 찾으실 수 있습니다:
- Expo에서의 위치 정보 획득 관련 오류 해결: 다양한 상황에서의 오류 해결책을 제공하고 있습니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

dev님의 프로필 이미지
dev

작성한 질문수

질문하기