[flutter] 플러터에서 위치 정보를 이용한 주변 약국 검색 앱 만들기

이번에는 flutter를 사용하여 위치 정보를 이용하여 주변 약국을 찾는 간단한 앱을 만들어보겠습니다. flutter에서는 위치 정보를 가져오기 위해 geolocator 패키지를 사용할 수 있으며, 약국 검색을 위해 Google Places API를 통해 제공되는 데이터를 활용할 수 있습니다.

1. 필요한 패키지 설치하기

먼저, pubspec.yaml 파일에 다음과 같이 패키지를 추가합니다:

dependencies:
  geolocator: ^7.6.2
  http: ^0.14.0

이를 통해 geolocator와 http 패키지를 설치할 수 있습니다.

2. 위치 정보 가져오기

다음으로, 사용자의 현재 위치를 가져오기 위해 geolocator 패키지를 이용합니다. 아래는 사용자의 현재 위치를 가져와 출력하는 예시 코드입니다:

import 'package:geolocator/geolocator.dart';

void getCurrentLocation() async {
  Position position = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.high,
  );
  print('현재 위치: ${position.latitude}, ${position.longitude}');
}

3. Google Places API를 이용한 약국 검색

위치 정보를 가져왔다면, 이제 Google Places API를 통해 주변 약국을 검색할 수 있습니다. API 요청을 보내고 응답을 받아와 필요한 정보를 추출하는 과정을 아래 코드로 보여드리겠습니다:

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

Future<List<String>> fetchNearbyPharmacies(double lat, double lng) async {
  final apiKey = 'YOUR_API_KEY'; // Google Places API 키 입력
  final radius = 1000; // 1km 반경 내에서 검색
  final type = 'pharmacy';
  final url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$lat,$lng&radius=$radius&type=$type&key=$apiKey';

  final response = await http.get(Uri.parse(url));
  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    List<String> pharmacies = List<String>.from(data['results'].map((result) => result['name']));
    return pharmacies;
  } else {
    throw Exception('Failed to load nearby pharmacies');
  }
}

마무리

위 예시 코드를 활용하여 flutter 앱에서 위치 정보를 가져오고 Google Places API를 통해 주변 약국을 검색하는 기능을 구현할 수 있습니다. 이를 활용하여 화면에 결과를 표시하거나 추가적인 기능을 구현하여 사용자에게 보다 유용한 앱을 만들어보세요!