[flutter] 플러터 geolocator와 GPS를 이용한 위치 기반 날씨 정보 애플리케이션 개발 방법

지금부터는 플러터(Flutter)를 사용하여 Geolocator와 GPS를 이용하여 위치 기반 날씨 정보 애플리케이션을 개발하는 방법에 대해 알아보겠습니다.

1. Geolocator 패키지 설치

먼저, Geolocator 패키지를 설치해야 합니다. 터미널 또는 명령 프롬프트에서 아래의 명령어를 실행하여 패키지를 설치할 수 있습니다.

flutter pub add geolocator

혹은 pubspec.yaml 파일에 직접 추가할 수도 있습니다.

dependencies:
  geolocator: ^7.0.3

2. 위치 권한 설정

애플리케이션이 위치 정보에 접근하기 위해서는 위치 권한이 필요합니다. 따라서, AndroidManifest.xml 파일(Android) 또는 Info.plist 파일(iOS)에 위치 권한을 설정해주어야 합니다.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location access is required for displaying weather information</string>

3. Geolocator를 사용한 위치 정보 가져오기

Geolocator는 플러터에서 제공하는 위치 정보를 쉽게 가져올 수 있는 패키지입니다. 이를 사용하여 애플리케이션에서 현재 위치를 가져올 수 있습니다. 다음은 위치 정보를 가져오고 출력하는 예시 코드입니다.

import 'package:geolocator/geolocator.dart';

void getLocation() async {
  Position position = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.high,
  );

  print('Latitude: ${position.latitude}');
  print('Longitude: ${position.longitude}');
}

위 코드에는 Geolocator.getCurrentPosition 함수를 사용하여 현재 위치를 가져오는 부분이 있습니다. desiredAccuracy 매개변수를 통해 위치의 정확도를 설정할 수 있으며, LocationAccuracy.high를 사용하면 높은 정확도로 위치 정보를 가져올 수 있습니다.

4. 날씨 정보 API 사용

위치 정보를 가져왔으면 이제 해당 위치의 날씨 정보를 가져오는 부분을 구현해야 합니다. 이를 위해 날씨 정보 API를 사용할 수 있습니다. 예를 들어, OpenWeatherMap API를 사용하여 날씨 정보를 가져올 수 있습니다.

import 'package:http/http.dart' as http;
import 'dart:convert';

void getWeather(double latitude, double longitude) async {
  String apiKey = 'YOUR_API_KEY';
  String apiUrl = 'https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey';
  
  http.Response response = await http.get(Uri.parse(apiUrl));

  if (response.statusCode == 200) {
    Map<String, dynamic> data = jsonDecode(response.body);
    String weatherDescription = data['weather'][0]['description'];

    print('Weather: $weatherDescription');
  } else {
    print('Failed to get weather data');
  }
}

위 코드에서는 OpenWeatherMap API를 사용하여 위도(latitude)와 경도(longitude)를 이용하여 해당 위치의 날씨 정보를 가져오는 부분이 있습니다. YOUR_API_KEY 부분에는 OpenWeatherMap API에서 발급받은 개인 키(API Key)를 입력해야 합니다.

5. 전체 코드

지금까지 작성한 기능을 통합하여 전체 코드를 작성해보겠습니다.

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Weather App'),
        ),
        body: Center(
          child: ElevatedButton(
            child: Text('Get Weather'),
            onPressed: () {
              getLocation();
            },
          ),
        ),
      ),
    );
  }

  void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );

    getWeather(position.latitude, position.longitude);
  }

  void getWeather(double latitude, double longitude) async {
    String apiKey = 'YOUR_API_KEY';
    String apiUrl = 'https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$apiKey';
  
    http.Response response = await http.get(Uri.parse(apiUrl));

    if (response.statusCode == 200) {
      Map<String, dynamic> data = jsonDecode(response.body);
      String weatherDescription = data['weather'][0]['description'];

      showDialog(
        builder: (context) => AlertDialog(
          title: Text('Weather'),
          content: Text('Current weather: $weatherDescription'),
          actions: [
            TextButton(
              child: Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
      );
    } else {
      print('Failed to get weather data');
    }
  }
}

위 코드에서는 getLocation 함수를 호출하는 ElevatedButton 위젯을 포함한 기본적인 애플리케이션 UI를 작성하였습니다. getLocation 함수를 통해 현재 위치를 가져오고, getWeather 함수를 통해 해당 위치의 날씨 정보를 가져와서 AlertDialog로 출력하는 기능도 포함되어 있습니다.

이제 애플리케이션을 실행하고 “Get Weather” 버튼을 클릭하면 현재 위치의 날씨 정보가 나타납니다.

6. 결론

위의 방법을 통해 플러터와 Geolocator를 사용하여 위치 기반 날씨 정보 애플리케이션을 개발할 수 있습니다. Geolocator로 위치 정보를 가져오고, 날씨 정보 API를 사용하여 해당 위치의 날씨 정보를 가져올 수 있습니다.

더 자세한 내용은 Geolocator 패키지OpenWeatherMap API 문서를 참고하시기 바랍니다.