내 위치 위도,경도 구하기 (geolocator)

oen·2022년 1월 6일
1

🇫 Flutter

목록 보기
3/14

https://pub.dev/packages/geolocator

1. 플러그인 설치

# pubspec.yaml

dependencies:
  geolocator: ^8.0.1

2. compileSdkVersion 변경

# android/app/build.gradle

android {
    compileSdkVersion 31

3. Permission 추가

안드로이드
# android/app/src/debug/AndroidManifest.xml

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

ios
# ios/Runner/Info.plist

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>This app needs access to location when open.</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>This app needs access to location when in the background.</string>

4. 위도, 경도 구하기

# lib/screens/map_screen.dart

import 'package:givewang/services/location.dart';

class _MapScreenState extends State<MapScreen> {
  
  void initState() {
    super.initState();

    getLocationData();
  }

  void getLocationData() async {
    Location location = Location();
    await location.getCurrentLocation();
    print(location.latitude);
    print(location.longitude);
  }

# lib/services/location.dart

import 'package:geolocator/geolocator.dart';

class Location {
  double latitude = 0;
  double longitude = 0;

  Future<void> getCurrentLocation() async {
    LocationPermission permission = await Geolocator.checkPermission();
    // print(permission);
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }
    try {
      Position position = await Geolocator.getCurrentPosition(
          desiredAccuracy: LocationAccuracy.high);
      latitude = position.latitude;
      longitude = position.longitude;
    } catch (e) {
      print(e);
    }
  }
}
profile
🐾

0개의 댓글