[flutter] 플러터에서 지도 최적 경로 계산하기

플러터를 사용하여 지도에서 최적 경로를 계산하는 방법을 알아봅니다. 이를 위해 Google Maps APIflutter_polyline_points 패키지를 사용할 것입니다.

1. Google Cloud 계정 및 API 키 설정

먼저 Google Cloud Console에서 새로운 프로젝트를 생성하고 Maps JavaScript APIDirections API를 활성화합니다. 그런 다음 API 키를 생성하고 프로젝트에 연결합니다.

2. flutter_polyline_points 패키지 설치

pubspec.yaml 파일에 다음을 추가하여 패키지를 설치합니다.

dependencies:
  flutter_polyline_points: ^0.2.8

그런 다음 flutter pub get 명령을 실행하여 패키지를 다운로드하고 설치합니다.

3. 지도 및 경로 표시

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';

GoogleMapController _controller;
Set<Polyline> _polylines = {};
List<LatLng> _polylineCoordinates = [];

final Set<Marker> _markers = {};

void _onMapCreated(GoogleMapController controller) {
  _controller = controller;

  // Add markers for origin and destination
  _markers.add(Marker(
    markerId: MarkerId('origin'),
    position: LatLng(37.7749, -122.4194),
  ));
  _markers.add(Marker(
    markerId: MarkerId('destination'),
    position: LatLng(34.0522, -118.2437),
  ));

  // Draw the route between origin and destination
  _getPolyline();
}

_getPolyline() async {
  PolylinePoints polylinePoints = PolylinePoints();
  PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
    "YOUR_API_KEY",
    PointLatLng(37.7749, -122.4194),
    PointLatLng(34.0522, -118.2437),
  );

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

    setState(() {
      _polylines.add(Polyline(
        width: 5,
        polylineId: PolylineId("poly"),
        color: Colors.blue,
        points: _polylineCoordinates,
      ));
    });
  }
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: GoogleMap(
      onMapCreated: _onMapCreated,
      initialCameraPosition: CameraPosition(
        target: LatLng(37.7749, -122.4194),
        zoom: 7.0,
      ),
      polylines: _polylines,
      markers: _markers,
    ),
  );
}

기본 지도를 생성하고 출발지와 도착지를 나타내는 마커를 추가한 후, flutter_polyline_points를 사용하여 출발지와 도착지 사이의 최적 경로 좌표를 가져와 지도에 표시합니다.

이제 플러터를 사용하여 지도에서 최적 경로를 계산하고 표시하는 방법을 알게 되었습니다. 다양한 옵션을 적용하여 사용자 경험을 더욱 향상시킬 수 있습니다.

참고 자료