[flutter] 플러터에서 위치 정보를 이용한 길 안내 앱 만들기

플러터는 구글에서 개발한 크로스 플랫폼 모바일 앱 개발 프레임워크로, 다양한 기기와 운영체제에서 작동하는 애플리케이션을 쉽게 만들 수 있습니다. 이번에는 플러터를 사용하여 위치 정보를 이용한 길 안내 앱을 만들어보겠습니다.

목표

이번 길 안내 앱은 사용자의 현재 위치를 기반으로 주변의 관광명소나 음식점, 카페 등을 찾아주고, 해당 장소까지의 길을 안내해주는 기능을 가지고 있을 것입니다.

위치 정보 사용하기

먼저 앱에서 위치 정보를 사용하기 위해 geolocator 패키지를 사용할 것입니다. 이 패키지를 이용하면 사용자의 현재 위치를 가져오거나 지정된 위치까지의 거리를 계산할 수 있습니다.

다음은 geolocator 패키지를 이용하여 사용자의 현재 위치를 가져오는 예시 코드입니다:

import 'package:geolocator/geolocator.dart';

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

지도 표시하기

다음으로 앱에서 위치 정보를 지도 상에 표시하기 위해 google_maps_flutter 패키지를 사용할 것입니다. 이 패키지를 이용하면 지도를 표시하고 마커를 추가하여 위치를 시각적으로 나타낼 수 있습니다.

다음은 google_maps_flutter 패키지를 이용하여 지도를 표시하고 마커를 추가하는 예시 코드입니다:

import 'package:google_maps_flutter/google_maps_flutter.dart';

GoogleMapController mapController;

GoogleMap(
  onMapCreated: (controller) {
    mapController = controller;
  },
  initialCameraPosition: CameraPosition(
    target: LatLng(37.7749, -122.4194),
    zoom: 10.0,
  ),
  markers: {
    Marker(
      markerId: MarkerId('marker1'),
      position: LatLng(37.7749, -122.4194),
      infoWindow: InfoWindow(
        title: 'San Francisco',
        snippet: 'An interesting city',
      ),
    ),
  },
);

길 안내 기능 추가하기

마지막으로 앱에서 사용자의 현재 위치와 선택된 장소 사이의 길을 안내해주는 기능을 추가할 것입니다. 이를 위해 flutter_polyline_points 패키지를 사용하여 두 지점 간의 좌표를 구하고, 이를 기반으로 안내선을 그릴 것입니다.

다음은 flutter_polyline_points 패키지를 이용하여 두 지점 간의 좌표를 구하고 안내선을 그리는 예시 코드입니다:

import 'package:flutter_polyline_points/flutter_polyline_points.dart';

List<LatLng> polylineCoordinates = [];

PolylinePoints polylinePoints = PolylinePoints();

PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
  apiKey,
  PointLatLng(startLatitude, startLongitude),
  PointLatLng(destinationLatitude, destinationLongitude),
);

if (result.points.isNotEmpty) {
  result.points.forEach((PointLatLng point) {
    polylineCoordinates.add(LatLng(point.latitude, point.longitude));
  });
}

마치며

플러터를 사용하여 위치 정보를 이용한 길 안내 앱을 만들어보았습니다. geolocatorgoogle_maps_flutter 패키지를 사용하여 위치 정보를 표시하고, flutter_polyline_points 패키지를 이용하여 두 지점 사이의 경로를 가져와서 지도 상에 표시하는 기능을 구현했습니다. 이러한 기능을 추가하여 사용자가 원하는 장소까지 쉽게 길을 찾을 수 있는 편리한 앱을 만들 수 있을 것입니다.

참고 문서: