Flutter를 사용하여 현재 GPS 위치를 얻는 방법

이 튜토리얼에서는 Flutter 앱에서 현재 GPS 위치정보, 즉 경도와 위도를 얻는 방법을 알아봅니다. 또한 GPS 위치(경도 및 위도 변경)를 자동으로 듣는 방법도 설명했습니다.

먼저 pubspect.yaml 파일에 다음 줄을 추가하여 프로젝트에 위치정보 Flutter 패키지를 추가해야 합니다 .

dependencies:
  flutter:
    sdk: flutter
  geolocator: ^8.0.0

android/app/src/main/AndroidManifest.xml에 있는 AndroidManifest.xml 파일 에 이 권한을 추가하세요.

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

수입:

import 'package:geolocator/geolocator.dart';

GPS가 활성화되었는지 확인하는 방법:

bool servicestatus = await Geolocator.isLocationServiceEnabled();

if(servicestatus){
   print("GPS service is enabled");
}else{
   print("GPS service is disabled.");
}

비동기식 방법을 사용하여 GPS 서비스의 활성화 또는 비활성화 여부를 확인할 수 있습니다. Geolocator.isLocationServiceEnabled();

위치 권한 확인 또는 위치 권한 요청 방법:

LocationPermission permission = await Geolocator.checkPermission();

if (permission == LocationPermission.denied) {
    permission = await Geolocator.requestPermission();
    if (permission == LocationPermission.denied) {
        print('Location permissions are denied');
    }else if(permission == LocationPermission.deniedForever){
        print("'Location permissions are permanently denied");
    }else{
        print("GPS Location service is granted");
    }
}else{
    print("GPS Location permission granted.");
}

Geolocator.checkPermission()권한이 부여되지 않은 경우 권한을 확인하거나 권한을 요청할  수  있습니다 Geolocator.requestPermission().

Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.longitude); //Output: 80.24599079
print(position.latitude); //Output: 29.6593457

String long = position.longitude.toString();
String lat = position.latitude.toString();

를 사용하여 경도 및 위도와 같은 현재 GPS 위치를 얻을 수 있습니다  Geolocator.getCurrentPosition().

GPS 위치를 듣는 방법: 경도 및 위도 변경 스트림:

import 'dart:async';
LocationSettings locationSettings = LocationSettings(
      accuracy: LocationAccuracy.high, //accuracy of the location data
      distanceFilter: 100, //minimum distance (measured in meters) a 
                            //device must move horizontally before an update event is generated;
);

StreamSubscription<Position> positionStream = Geolocator.getPositionStream(
      locationSettings: locationSettings).listen((Position position) {
      print(position.longitude); //Output: 80.24599079
      print(position.latitude); //Output: 29.6593457

      String long = position.longitude.toString();
      String lat = position.latitude.toString();
});

여기서 Geolocator는 위치 변경에 대한 데이터를 자동으로 보냅니다. 

전체 Flutter/Dart 앱 코드 예:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  bool servicestatus = false;
  bool haspermission = false;
  late LocationPermission permission;
  late Position position;
       String long = "", lat = "";
  late StreamSubscription<Position> positionStream;

   @override
  void initState() {
    checkGps();
    super.initState();
  }

  checkGps() async {
      servicestatus = await Geolocator.isLocationServiceEnabled();
      if(servicestatus){
            permission = await Geolocator.checkPermission();
          
            if (permission == LocationPermission.denied) {
                permission = await Geolocator.requestPermission();
                if (permission == LocationPermission.denied) {
                    print('Location permissions are denied');
                }else if(permission == LocationPermission.deniedForever){
                    print("'Location permissions are permanently denied");
                }else{
                   haspermission = true;
                }
            }else{
               haspermission = true;
            }

            if(haspermission){
                setState(() {
                  //refresh the UI
                });

                getLocation();
            }
      }else{
        print("GPS Service is not enabled, turn on GPS location");
      }

      setState(() {
         //refresh the UI
      });
  }

  getLocation() async {
      position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
      print(position.longitude); //Output: 80.24599079
      print(position.latitude); //Output: 29.6593457

      long = position.longitude.toString();
      lat = position.latitude.toString();

      setState(() {
         //refresh UI
      });

      LocationSettings locationSettings = LocationSettings(
            accuracy: LocationAccuracy.high, //accuracy of the location data
            distanceFilter: 100, //minimum distance (measured in meters) a 
                                 //device must move horizontally before an update event is generated;
      );

      StreamSubscription<Position> positionStream = Geolocator.getPositionStream(
            locationSettings: locationSettings).listen((Position position) {
            print(position.longitude); //Output: 80.24599079
            print(position.latitude); //Output: 29.6593457

            long = position.longitude.toString();
            lat = position.latitude.toString();

            setState(() {
              //refresh UI on update
            });
      });
  }

  @override
  Widget build(BuildContext context) {
   
    return Scaffold(
         appBar: AppBar(
            title: Text("Get GPS Location"),
            backgroundColor: Colors.redAccent
         ),
          body: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(50),
             child: Column(
                children: [ 

                     Text(servicestatus? "GPS is Enabled": "GPS is disabled."),
                     Text(haspermission? "GPS is Enabled": "GPS is disabled."),
                     
                     Text("Longitude: $long", style:TextStyle(fontSize: 20)),
                     Text("Latitude: $lat", style: TextStyle(fontSize: 20),)

                ]
              )
          )
    );
  } 
}

이런 방식으로 현재 GPS 위치를 얻거나 Flutter 앱에서 GPS 위치 변경을 지속적으로 들을 수 있습니다. 

1.05 GEEK