Flutter: Creating a route calculator using Google Maps

Souvik Biswas
Flutter Community
Published in
9 min readJun 7, 2020

If you want to conveniently convey details of places, directions, and routes to the end-user, Google Maps is an essential part of your app. Luckily, there is an official Google Maps plugin available for Flutter.

In this article, I will show you how to integrate Google Maps in Flutter to find a route between two places and calculate its distance.

The topics that I am going to cover in this article are:

  • Create & set up a new Google Cloud Platform (GCP) project
  • Add Google Maps SDK (for both Android & iOS) and Directions API to the GCP project
  • Create an API Key on GCP
  • Setup Flutter project to use Google Maps
  • Add Google Maps widget
  • Use Geocoding to translate coordinates into a place address and vice versa
  • Use Polylines for drawing route between two places
  • Calculate distance of that route

There’s a lot to learn from this article. So, bear with me and follow along.

Creating a GCP project

You will need a GCP project for getting access to the Google Maps API and for generating the API key.

NOTE: If you have never used GCP before, you will have to setup a Billing account. You can follow the official guide here.

Follow the steps below for creating a new GCP project:

  1. Go to GCP Console.
  2. Go to Project Selection dialog-box and click New Project.

3. Enter a name for your project and click Create.

This will create a new GCP project.

Enabling APIs

In order to use Google Maps in your app, you will need to enable Maps SDK for both the platforms.

  1. Go to APIs & Services from the left menu and select Library.

2. Now, search for Maps and enable Maps SDK for both platforms.

3. You will also need the Directions API while drawing the routes. So enable that as well.

Generating an API key

You will need an API key for integrating Google Maps into your app.

  1. Go to APIs & Services from the left menu and select Credentials.

2. Click CREATE CREDENTIALS and select API key.

This will generate an API key for the project, you will need this in the next step.

Set up the Flutter project

  • Create a new Flutter project.
flutter create flutter_maps
  • Open the project using your favorite IDE. For opening with VS Code:
code flutter_maps
google_maps_flutter: ^0.5.28+1

Android setup

  • Navigate to the file android/app/src/main/AndroidManifest.xml and add the following code snippet inside the application tag:
<!-- Add your Google Maps API Key here -->
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR KEY HERE"/>
  • You will also need location access in the app. So, add the following permission in the same file inside the manifest tag:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

iOS setup

  • Navigate to the file ios/Runner/AppDelegate.swift and replace the whole code with the following:
  • Also, add the following to ios/Runner/Info.plist file:
<key>io.flutter.embedded_views_preview</key> 
<string>YES</string>
  • To get the location permission, add the following to the same file:
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

This completes the setup for both the platforms in Flutter.

Integrating the Google Maps Widget

Now, you are ready to add Google Maps Widget to your Flutter app.

You can start with the following code:

I have defined the Container height and width to be the size of the screen so that the Google Maps widget takes up the entire space of the screen.

I am using a Stack to keep Google Maps widget in the background and add other necessary widgets on top of it.

Now, replace the TODO in the above code snippet with the Google Maps widget.

  • initialCameraPosition: This is a required parameter that is used for loading the Map view on initial startup.
  • myLocationEnabled: For showing your current location on Map with a blue dot.
  • myLocationButtonEnabled: Button used for bringing the user location to the center of the camera view.
  • mapType: For specifying the type of map to display (normal, satellite, hybrid & terrain).
  • zoomGesturesEnabled: Whether the map view should respond to zoom gestures.
  • zoomControlsEnabled: Whether to show zoom controls (only applicable for Android platform).
  • onMapCreated: Callback for when the map is ready to use.

I have set the myLocationButtonEnabled and zoomControlsEnabled to false because I am going to show you how to define a custom button with the same functionality but with better control.

The mapController would be used for controlling the camera position of the Map view.

By now, the app looks like this:

To display the zoom buttons and the current location button you can add them as a child to the Stack widget and position them accordingly.

The code for design of a button is given below:

Other buttons have a similar design.

You can take a look at the code snippet for the design and positioning of the zoom buttons here and current location button here.

Using zoom in the map view

You can use the mapController to perform a simple Zoom In and Zoom Out action.

Move to a new position

For moving to a new position you can use the following code snippet:

Here, I have specified only the target & zoom property of the CameraPosition widget. But there are two more properties, bearing & tilt that you may use.

In the target property, you have to pass the latitude and longitude of the position you want to move.

Here, we need the Current Location button to move the camera view to the user’s present location. Let’s see how to achieve that.

After adding the buttons, the app will look like this:

Fetching current location

There is a nice plugin for Flutter, known as geolocator that can help you to fetch user’s current location easily.

Add it to your pubspec.yaml file:

geolocator: ^5.3.1

Now let’s get started and go through it step-by-step.

  1. Initialize Geolocator and define a variable.

2. Get the current location of the user.

3. Add this method to the initState in order to fetch the current location of the user as soon as the app launches, and also move the camera to the detected location.

4. Also, pass the latitude & longitude to the onTap method of the custom button for fetching the user's current location.

After completing these, the camera will automatically move to the detected location as the app launches.

Geocoding

When you have the initial app setup and working, now you can move on to adding two places and detecting their route on Map. For this, you will need the latitude and longitude of the two places. But, for any user knowing the geographic coordinates of a place is a hard task. So, here comes Geocoding.

Geocoding is a technique by which the address of a place can be converted to their coordinates (latitude & longitude) and vice versa.

The Flutter package geolocator also supports Geocoding. For getting started with geocoding, you will need to take the addresses as user inputs using TextField.

You can find the code for the design of the TextField here.

If you want to show the address of the starting location, then you have to define a TextEditingController for the starting address and update the text as soon as the address of the user's present location is retrieved.

You can retrieve the address of the starting location by using the following method:

You can use a similar method for retrieving the coordinates from the starting address and the destination address. You will require these coordinates in order to draw a route on the Map and for placing Markers.

Placing Markers

You can use the coordinates retrieved in the previous step for placing Markers on the Map.

  • First of all, define a variable for storing the markers:
  • Create the markers:
  • Add the markers:
  • Display the markers on the map:

If you run the app now, it will look like this:

You will notice that only one of the markers is visible, although you placed two of them, one at the starting point and the other at the destination.

So, what’s happening here?

Actually, both the Markers are added to the Map, but only one of them is visible because the other one is outside the Map View. If you zoom out a bit, you will notice the other one too.

You can use the following code snippet for reorienting the Map View to accommodate both the Markers.

Drawing a route

Polyline is used for drawing routes on Google Maps. It is a list of points where line segments are drawn between consecutive points.

There is a Flutter package available for drawing polylines, known as flutter_polyline_points. It uses the Directions API that you had enabled in the beginning.

  • Add the package to your pubspec.yaml file.
flutter_polyline_points: ^0.2.1
  • Define some variables.
  • Define a method for creating the polylines. You have to pass the starting and destination positions.
  • Display polyline on the Map.

After drawing the route, the app will look like this:

Calculating Distance

You have arrived at the last phrase of this project. With the markers properly positioned and the route drawn, you might want to calculate the distance between the two locations.

There is a method that comes with the geolocator package using which you can calculate the distance between two places just by providing their coordinates.

However, this method does not calculate the distance of the actual route. It uses the Haversine formula to calculate the distance based upon the supplied GPS coordinates.

You can find more information about this here.

What you can do, is break the entire route into several small parts and calculate their distances, then sum them up. Remember, you have already calculated the coordinates while drawing the polyline. You can use these coordinates to calculate the total distance of the route.

The formula that I have used for calculating the distance between two geographic coordinates is as follows:

Now, you can use this formula to calculate the distances between two coordinates and sum them up to find the total distance.

Show the calculated distance on the UI:

The final app will look like this:

Conclusion

There’s a lot more you can do using Google Maps and some of its supported APIs. I hope this article will help you to get started with Google Maps in Flutter.

You can find the GitHub repo for this project in the following link:

If you like this project, please give “Stars” (⭐️) to my GitHub repo.

--

--

Souvik Biswas
Flutter Community

Mobile Developer (Android, iOS & Flutter) | Technical Writer (FlutterFlow) | IoT Enthusiast | Avid video game player