Open In App

How to Add Route Polylines to Google Maps in Flutter?

Last Updated : 23 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Google Maps is used in many Android applications. We can use Polylines to represent routes for various destinations on Google Maps. So in this article, we are going to add Route Polylines to Google Maps in Flutter.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Generating API Key for Using Google Maps

Check out the below article on How to generate an API key for using Google Maps. After developing that key we have to use it within our project to integrate Google Maps. 

Now, follow the Steps to Implement Google Maps in the Flutter Application

Step 3: Adding Dependency to pubspec.yaml File

dependencies:
    flutter: 
    google_maps_flutter: ^2.1.8

Now click on pub.get to configure.

Step 4: Update build.gradle File

Navigate to android>app>build.gradle file and update code on below line. 

Change Compile SDK Version

android {
    compileSdkVersion 31

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

Change Min SDK Version

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.google_maps"
    minSdkVersion 20
    targetSdkVersion 30
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

Step 5: Add API Key to Android Manifest File

Navigate to android > app > src > main > AndrodManifest.xml file and add the below code in the manifest tag. Make sure to add your Google Maps API key in the value. 

<meta-data android:name="com.google.android.geo.API_KEY"
        android:value="Enter your API key here"/>

Step 6: Working with main.dart File

Navigate to lib > main.dart file and add the below code to it. Comments are added in the code to get to know in detail. 

Dart




import 'package:flutter/material.dart';
import 'package:google_maps/Convert_Lat_Long.dart';
 
void main() {
  runApp(const MyApp());
}
 
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
 
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // on below line we are specifying title of our app
      title: 'GFG',
      // on below line we are hiding debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // on below line we are specifying theme
        primarySwatch: Colors.green,
      ),
      // First screen of our app
      home: const HomePage(),
    );
  }
}


Step 7: Creating a new Dart File for Home Page

Navigate to lib > Right click on it > New > Dart File and name it as HomePage.dart. After creating that file add the below code to it. Comments are added in the code to get to know in detail.

Dart




import 'dart:async';
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
 
class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);
 
  @override
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  // created controller to display Google Maps
  Completer<GoogleMapController> _controller = Completer();
  //on below line we have set the camera position
  static final CameraPosition _kGoogle = const CameraPosition(
      target: LatLng(19.0759837, 72.8776559),
    zoom: 14,
  );
 
  final Set<Marker> _markers = {};
  final Set<Polyline> _polyline = {};
 
  // list of locations to display polylines
  List<LatLng> latLen = [
    LatLng(19.0759837, 72.8776559),
    LatLng(28.679079, 77.069710),
    LatLng(26.850000, 80.949997),
    LatLng(24.879999, 74.629997),
    LatLng(16.166700, 74.833298),
    LatLng(12.971599, 77.594563),
  ];
   
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
 
    // declared for loop for various locations
    for(int i=0; i<latLen.length; i++){
      _markers.add(
        // added markers
        Marker(
            markerId: MarkerId(i.toString()),
          position: latLen[i],
          infoWindow: InfoWindow(
            title: 'HOTEL',
            snippet: '5 Star Hotel',
          ),
          icon: BitmapDescriptor.defaultMarker,
        )
      );
      setState(() {
 
      });
      _polyline.add(
          Polyline(
            polylineId: PolylineId('1'),
            points: latLen,
            color: Colors.green,
          )
      );
    }
  }
   
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF0F9D58),
        // title of app
        title: Text("GFG"),
      ),
      body: Container(
        child: SafeArea(
          child: GoogleMap(
            //given camera position
              initialCameraPosition: _kGoogle,
            // on below line we have given map type
            mapType: MapType.normal,
            // specified set of markers below
            markers: _markers,
            // on below line we have enabled location
            myLocationEnabled: true,
            myLocationButtonEnabled: true,
            // on below line we have enabled compass location
            compassEnabled: true,
            // on below line we have added polylines
            polylines: _polyline,
            // displayed google map
            onMapCreated: (GoogleMapController controller){
                _controller.complete(controller);
            },
          ),
        ),
      ),
   );
  }
}


Output:

Adding Route Polylines to Google Maps in Flutter

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads