Flutter의 Google 지도에 Moving Maker의 폴리라인 트레일을 그리는 방법

이 튜토리얼에서는 Flutter의 Google 지도에서 마커를 한 위치에서 다른 위치로 이동하면서 마커 뒤에 폴리라인 트레일을 그리는 방법을 알아봅니다. 이 기능은 GPS 추적 또는 차량 추적 앱을 만드는 경우 중요한 요소입니다.

먼저 폴리라인 목록 변수를 선언합니다.

Set<Polyline> polylines={};

초기 위치:

LatLng loc1 = LatLng(27.6602292, 85.308027); 

이제 폴리라인의 시작 및 끝 위치에 대한 두 개의 위치 변수를 선언합니다.

late LatLng pos1; //positions for polylines
late LatLng pos2;

지금,

pos1 = loc1;
pos2 = loc1;

마커를 이동하는 동안:

pos1 = pos2;
pos2 = LatLng(new latitude, new longitude);

이제 모든 움직임에 대해 목록에 새로운 폴리라인을 추가하겠습니다.

polylines.add(Polyline(
    polylineId: PolylineId(pos2.toString()),
    visible: true,
    width: 5, //width of polyline
    points: [
        pos1,
        pos2,
    ],
    color: Colors.deepPurpleAccent, //color of polyline
));

이제 Google 지도에 폴리라인을 표시해 보세요.

GoogleMap( 
     polylines: polylines, //polylines list
)

전체 앱 예:

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

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  GoogleMapController? mapController; //contrller for Google map
  Set<Marker> markers = Set(); //markers for google map
  Set<Polyline> polylines={};

  LatLng loc1 = LatLng(27.6602292, 85.308027);  

  int numDeltas = 50; //number of delta to devide total distance
  int delay = 50; //milliseconds of delay to pass each delta
  var i = 0;
  double? deltaLat; 
  double? deltaLng;
  var position; //position variable while moving marker

  late LatLng pos1; //positions for polylines
  late LatLng pos2;

  @override
  void initState() {
    position = [loc1.latitude, loc1.longitude]; //initial position of moving marker
    pos1 = loc1;
    pos2 = loc1;
    addMarkers();
    super.initState();
  }

  addMarkers() async {
      markers.add(
        Marker( 
          markerId: MarkerId(loc1.toString()),
          position: loc1, 
          icon: BitmapDescriptor.defaultMarker
        )
      );

      setState(() {
          //refresh UI
      });
  }

  transition(result){
      i = 0;
      deltaLat = (result[0] - position[0])/numDeltas;
      deltaLng = (result[1] - position[1])/numDeltas;
      moveMarker();
  }

  moveMarker(){
      position[0] += deltaLat;
      position[1] += deltaLng;
      var latlng = LatLng(position[0], position[1]);
      
      markers = {
        Marker(
            markerId: MarkerId("movingmarker"),
            position: latlng,
            icon: BitmapDescriptor.defaultMarker,
        )
      };

        pos1 = pos2;
        pos2 = LatLng(position[0], position[1]);
        
        polylines.add(Polyline(
            polylineId: PolylineId(pos2.toString()),
            visible: true,
            width: 5, //width of polyline
            points: [
               pos1,
               pos2,
            ],
            color: Colors.deepPurpleAccent, //color of polyline
        ));

      setState(() {
         //refresh UI
      });
    

      if(i!=numDeltas){
          i++;
          Future.delayed(Duration(milliseconds: delay), (){
              moveMarker();
          });
      }
  }

  
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
          appBar: AppBar( 
             title: Text("Move Marker Position on Google Map"),
             backgroundColor: Colors.deepPurpleAccent,
          ),
          floatingActionButton: FloatingActionButton(
             child: Text("Move"),
             onPressed: (){
                 var result = [27.661838, 85.308543];
                 //latitude and longitude of new position

                 transition(result);
                 //start moving marker
             },
          ),
          body: GoogleMap( //Map widget from google_maps_flutter package
                  zoomGesturesEnabled: true, //enable Zoom in, out on map
                  initialCameraPosition: CameraPosition( //innital position in map
                    target: loc1, //initial position
                    zoom: 14.0, //initial zoom level
                  ),
                  markers: markers, //markers to show on map
                  polylines: polylines, //polylines list
                  mapType: MapType.normal, //map type
                  onMapCreated: (controller) { //method called when map is created
                    setState(() {
                      mapController = controller; 
                    });
                  },
          )
       );
  }
}

이러한 방식으로 Google 지도의 한 위치에서 다른 위치로 마커를 이동하는 동안 마커 뒤에 폴리라인 트레일을 그릴 수 있습니다.

1.55 GEEK