[flutter] 플러터에서 위치 정보를 이용한 근처 카페 검색 앱 만들기

플러터(Flutter)를 사용하여 위치 정보를 활용하여 근처 카페를 검색하는 앱을 만드는 방법에 대해 알아보겠습니다.

목표

  1. 사용자의 현재 위치를 파악하여 지도에 표시
  2. 위치 기반 서비스를 통해 근처 카페를 검색하여 목록으로 표시
  3. 선택된 카페의 상세 정보를 확인할 수 있는 기능 제공

필요 도구

단계별 진행

1. 위치 정보 설정

플러터 앱에서 위치 정보를 사용하기 위해 location 패키지를 이용합니다.

import 'package:location/location.dart';

// 위치 정보 가져오기
Location location = Location();
LocationData currentLocation;

void getCurrentLocation() async {
  try {
    currentLocation = await location.getLocation();
  } catch (e) {
    // 위치 정보 가져오기 실패 시 처리
  }
}

2. 지도에 현재 위치 표시

google_maps_flutter 패키지를 사용하여 지도에 현재 위치를 표시합니다.

import 'package:google_maps_flutter/google_maps_flutter.dart';

GoogleMapController mapController;
Marker marker;

GoogleMap(
  onMapCreated: (GoogleMapController controller) {
    mapController = controller;
  },
  initialCameraPosition: CameraPosition(
    target: LatLng(currentLocation.latitude, currentLocation.longitude),
    zoom: 15.0,
  ),
  markers: Set<Marker>.from([Marker(
    markerId: MarkerId("currLocation"),
    position: LatLng(currentLocation.latitude, currentLocation.longitude),
  )]),
);

3. 근처 카페 검색 및 목록 표시

위치 기반 서비스를 통해 근처의 카페 정보를 가져와 목록으로 표시합니다.

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

List cafes;

void fetchNearbyCafes() async {
  final response = await http.get(Uri.parse('https://api.example.com/nearbycafes?lat=${currentLocation.latitude}&lng=${currentLocation.longitude}'));

  if (response.statusCode == 200) {
    cafes = json.decode(response.body);
  } else {
    throw Exception('Failed to load nearby cafes');
  }
}

4. 선택된 카페의 상세 정보 확인

카페를 선택하면 해당 카페의 상세 정보를 확인할 수 있도록 합니다.

// 카페 목록 화면에서 해당 카페 선택 시
void onCafeSelected(int index) {
  String selectedCafeId = cafes[index]['id'];
  // 카페 상세 정보 페이지로 이동
}

위와 같은 방법으로 위치 정보를 활용한 근처 카페 검색 앱을 만들 수 있습니다. 플러터를 사용하면 효율적으로 위치 기반 서비스를 활용하여 다양한 앱을 개발할 수 있습니다.