How to Draw Route Direction Polylines on Google Map in Flutter

In this example, we are going to show you how to fetch polyline points from Google Map Direction API and draw routes paths between two locations coordinates on Google Map in Flutter App. 

Before starting, be sure you know very well to integrate Google Map in the Flutter app.

To draw route path polylines on Google Maps, get the API KEY from the Google console, and enable the following APIs.

Now get the API KEY as well from the "credentials" section.

Now, in AndroidManifest.xml file, add API Key like below:

<application
   android:label="testapp"
   android:icon="@mipmap/ic_launcher">

   <meta-data android:name="com.google.android.geo.API_KEY"  
             android:value="YOUR MAP API KEY"/>
  
 <activity  
     android:name=".MainActivity"

In iOS, Add your code like below in ios/Runner/AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Now, add google_maps_flutter, flutter_polyline_points Flutter packages in your project by adding the following lines in pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  google_maps_flutter: ^2.1.1
  flutter_polyline_points: ^1.0.0

Set<Marker> markers = Set(); //markers for google map

LatLng startLocation = LatLng(27.6683619, 85.3101895);  
LatLng endLocation = LatLng(27.6688312, 85.3077329);
markers.add(Marker( //add start location marker
  markerId: MarkerId(startLocation.toString()),
  position: startLocation, //position of marker
  infoWindow: InfoWindow( //popup info 
    title: 'Starting Point ',
    snippet: 'Start Marker',
  ),
  icon: BitmapDescriptor.defaultMarker, //Icon for Marker
));

markers.add(Marker( //add distination location marker
  markerId: MarkerId(endLocation.toString()),
  position: endLocation, //position of marker
  infoWindow: InfoWindow( //popup info 
    title: 'Destination Point ',
    snippet: 'Destination Marker',
  ),
  icon: BitmapDescriptor.defaultMarker, //Icon for Marker
));
GoogleMap( 
    markers: markers, //markers to show on map
),

PolylinePoints polylinePoints = PolylinePoints();
String googleAPiKey = "GOOGLE API KEY";
Map<PolylineId, Polyline> polylines = {};

LatLng startLocation = LatLng(27.6683619, 85.3101895);  
LatLng endLocation = LatLng(27.6688312, 85.3077329); 
List<LatLng> polylineCoordinates = [];
     
PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
    googleAPiKey,
    PointLatLng(startLocation.latitude, startLocation.longitude),
    PointLatLng(endLocation.latitude, endLocation.longitude),
    travelMode: TravelMode.driving,
);

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

addPolyLine(polylineCoordinates);
addPolyLine(List<LatLng> polylineCoordinates) {
  PolylineId id = PolylineId("poly");
  Polyline polyline = Polyline(
    polylineId: id,
    color: Colors.deepPurpleAccent,
    points: polylineCoordinates,
    width: 8,
  );
  polylines[id] = polyline;
  setState(() {});
}
GoogleMap(
    polylines: Set<Polyline>.of(polylines.values),
)

See the final code below, use the example as a reference to draw Direction Routes polylines on Google map in Flutter App.

If your polyline is not drawn, then have a look at How to Solve Poly Line Not Drawing on Google Map Flutter

import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.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
  PolylinePoints polylinePoints = PolylinePoints();

  String googleAPiKey = "GOOGLE MAP API KEY";
  
  Set<Marker> markers = Set(); //markers for google map
  Map<PolylineId, Polyline> polylines = {}; //polylines to show direction

  LatLng startLocation = LatLng(27.6683619, 85.3101895);  
  LatLng endLocation = LatLng(27.6688312, 85.3077329); 
                            

  @override
  void initState() {

     markers.add(Marker( //add start location marker
        markerId: MarkerId(startLocation.toString()),
        position: startLocation, //position of marker
        infoWindow: InfoWindow( //popup info 
          title: 'Starting Point ',
          snippet: 'Start Marker',
        ),
        icon: BitmapDescriptor.defaultMarker, //Icon for Marker
      ));

      markers.add(Marker( //add distination location marker
        markerId: MarkerId(endLocation.toString()),
        position: endLocation, //position of marker
        infoWindow: InfoWindow( //popup info 
          title: 'Destination Point ',
          snippet: 'Destination Marker',
        ),
        icon: BitmapDescriptor.defaultMarker, //Icon for Marker
      ));
      
      getDirections(); //fetch direction polylines from Google API
      
    super.initState();
  }

  getDirections() async {
      List<LatLng> polylineCoordinates = [];
     
      PolylineResult result = await polylinePoints.getRouteBetweenCoordinates(
          googleAPiKey,
          PointLatLng(startLocation.latitude, startLocation.longitude),
          PointLatLng(endLocation.latitude, endLocation.longitude),
          travelMode: TravelMode.driving,
      );

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

  addPolyLine(List<LatLng> polylineCoordinates) {
    PolylineId id = PolylineId("poly");
    Polyline polyline = Polyline(
      polylineId: id,
      color: Colors.deepPurpleAccent,
      points: polylineCoordinates,
      width: 8,
    );
    polylines[id] = polyline;
    setState(() {});
  }
  
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
          appBar: AppBar( 
             title: Text("Route Driection in Google Map"),
             backgroundColor: Colors.deepPurpleAccent,
          ),
          body: GoogleMap( //Map widget from google_maps_flutter package
                    zoomGesturesEnabled: true, //enable Zoom in, out on map
                    initialCameraPosition: CameraPosition( //innital position in map
                      target: startLocation, //initial position
                      zoom: 16.0, //initial zoom level
                    ),
                    markers: markers, //markers to show on map
                    polylines: Set<Polyline>.of(polylines.values), //polylines
                    mapType: MapType.normal, //map type
                    onMapCreated: (controller) { //method called when map is created
                      setState(() {
                        mapController = controller; 
                      });
                    },
              ),
       );
  }
}

In this way, you can draw Direction routes polyline paths on Google Map in Flutter app.

1 Commet on this Article

Ashwani

There is issue if coordinates is far away on such cases poly lines are not accurate 

11 months ago


Please Wait...