🌏 What is geolocator?

내 디바이스의 현재 위치를 찾는 데 사용되는 flutter package

📍 장치의 현재 위치 가져오기
📍 지속적인 위치 업데이트
📍 두 위치 사이 거리 계산 등의 기능을 제공한다


📦 installation

Flutter 공식 설치 가이드

# 프로젝트 디렉토리 최상단에서 실행
flutter pub add geolocator

제대로 설치되었다면 pubspec.yaml 파일에 다음 코드가 추가되며 암시적으로 flutter pub get이 실행된다

dependencies:
	geolocator: ^11.0.0

그리고 몇 가지 설정을 더 해주어야 위치정보를 사용할 수 있다(2024.05.15. 기준)

  1. Android
  • android/app/src/profile/AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  1. iOS
  • ios/Runner/Info.plist
<!-- indentation 주의 -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

❖ 백그라운드에서도 위치정보를 업데이트 받을 수 있도록 하는 설정은 문서 참조..

이제 Dart 파일에 다음 코드를 추가하면 geolocator를 사용할 수 있다!

import 'package:geolocator/geolocator.dart';

👩‍💻 Usage

import 'package:geolocator/geolocator.dart';

// 현재 위치 가져오기
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);

// 마지막으로 알려진 위치
Position? position = await Geolocator.getLastKnownPosition();

⛔️ Exceptions

  • MissingPluginException
    : 플러그인 설치 후 자주 발생하는 에러로 패키지를 정상적으로 읽어오지 못 해 발생
    : hot-reload, restart가 아니라 완전히 종료했다가 다시 시작하면 대체로 해결된다

flutter pub get이 동작 안했나..

  • PermissionDeniedException

    : 에러가 발생한 코드 상단에 하단의 코드를 추가한다
LocationPermission permission = await Geolocator.requestPermission();

→ 바로 위치 정보를 읽어올 때 권한 문제가 발생하기 때문에 권한을 먼저 얻은 후 geolocator 메서드를 사용하게끔 해주는 것이다.

📱 결과

위치 정보 출력 코드

이제 geolocator를 사용할 수 있게 되었다!


🎯 최종 코드

void getLocation() async {
  LocationPermission permission = await Geolocator.checkPermission();
  if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();

    if (permission == LocationPermission.denied) {
      return;
    }
  }

  Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high);
  print(position);
}
profile
😎노션 상주 중,,😎

0개의 댓글

Powered by GraphCDN, the GraphQL CDN