[Flutter] Flutter_map 패키지

uengmin·2025년 1월 10일

Flutter

목록 보기
15/20

이번에는 기존 maui로 개발했던 지도페이지를 Flutter로 포팅해보자.
maui에서는 Mapsui.UI.Maui를 사용해서 화면을 만들었다.

위의 화면은 실시간으로 사용자의 핸드폰 위치(위도,경도)를 서버로 전송하고 그 위치 정보를 서버에서 받아와 지도에 표시하는 것이다.

1. 설치

  • 우선 패키지부터 설치하자
 $ flutter pub add flutter_map

이렇게 하면 패키지의 pubspec.yaml 파일에 아래와 같은 줄이 추가된다.

dependencies:
 flutter_map: ^7.0.2
  • 그러면 아래의 패키지를 사용할 수 있게 된다.
import 'package:flutter_map/flutter_map.dart';

2. 지도

  • 우선 제일 중요한 지도를 불러와보자
FlutterMap(
  options: const MapOptions(
    // 지도 회전 금지 설정
    interactionOptions: InteractionOptions(
      flags: InteractiveFlag.drag | InteractiveFlag.pinchZoom,
    ),
    // 지도 초기 위치 설정
    initialCenter: LatLng(37.484418, 127.116639),
    // 지도 초기 줌 설정
    initialZoom: 10,
  ),
  children: [
    openStreetMapTileLayer,

이와 같이 하면 화면에 지도가 출력되게 된다.

3. Map Pin

  • 우선 지도에 Pin을 찍기 위해서는 위치 정보가 필요하다. 우선 DB 연결 전이기 때문에 하드 코딩으로 위치를 작성하였다.
  //pin 정보
  late final customMarkers = <Marker>[
    // DB에서 가져온 정보로 pin 생성
    buildPin(LatLng(37.484418, 127.416639), '1차', "2025-10-17 13:31:31"),
    buildPin(LatLng(37.784418, 127.316639), '2차', "2025-10-17 13:31:31"),
    buildPin(LatLng(37.684418, 127.216639), '3차', "2025-10-17 13:31:31"),
    buildPin(LatLng(37.284418, 127.116639), '4차', "2025-10-17 13:31:31"),
    buildPin(LatLng(37.884418, 127.016639), '5차', "2025-10-17 13:31:31"),
  ];
  
// pin
MarkerLayer(
     markers: customMarkers,
     rotate: counterRotate,
  ),
  // pin 생성
  Marker buildPin(LatLng point, String action, String time) => Marker(
        point: point,
        width: 50,
        height: 50,
        child: GestureDetector(
          onTap: () => ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('$time 기준\n$action 작업 진행하였습니다.'),
              duration: Duration(seconds: 2),
              showCloseIcon: true,
            ),
          ),
          child: const Icon(Icons.location_pin, size: 40, color: Colors.red),
        ),
      );
  • 위도와 경도를 DB에서 받아오거나 하드 코딩을 통해 customMarkers에 담아주고 MarkerLayer를 통해 지도에 표시해준다.
  • 그 다음 지도를 클릭했을 때 작업이 진행된 시간과 메시지를 토스트 메시지로 표시해주면 된다.

4.Polyline

  • 지도에 생성된 핀을 이어 보기 편하게 하기 위해 Polyline이 필요하다.
  //위치 정보
  final _polylinesRaw = <Polyline<HitValue>>[
    Polyline(
      points: [
        const LatLng(37.484418, 127.416639),
        const LatLng(37.784418, 127.316639),
        const LatLng(37.684418, 127.216639),
        const LatLng(37.284418, 127.116639),
        const LatLng(37.884418, 127.016639),
      ],
      strokeWidth: 500,
      color: Colors.black54,
      useStrokeWidthInMeter: true,
    ),
  ];
  • 마찬가지로 DB에서 받아오거나 하드코딩 해주면 되는데 선의 두께와 색상을 작성해준다.
// polyline 생성
MouseRegion(
  child: GestureDetector(
    child: PolylineLayer(
      simplificationTolerance: 0,
      polylines: [..._polylinesRaw],
    ),
  ),
),
  • 위 코드로 선을 그어준다.

결과

0개의 댓글