How to add Google Maps plugin in Flutter?
Tags: flutter, dart, beginners
Published: 2021-11-13 08:31:17

## Introduction
Nowadays, having a map interface in an application is quite common to efficiently convey details of places, directions and routes to the user. 

In this article, we will see how to integrate Google Maps plugin in Flutter using the [Google Maps Flutter](https://pub.dev/packages/google_maps_flutter) package.

## Table of contents
* Create a GCP project
* Add Google Maps SDK (for both Android & iOS)
* Create an API key
* Setup Flutter application
* Add Google Maps widget.

## Creating a GCP project
To use Google Maps plugin, we need a GCP project and its corresponding API key. To create a new GCP project, follow the below steps.

1. Head over to [GCP console](https://console.cloud.google.com).
2. Open `Select a project` dialog and click on `New Project`.
![Project select](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yf0vwrlndbdkif289gee.png)
3. Enter project name and click on `Create`.
![Project create](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uw40xqrcp993gx5av0yg.png)

With this, we have created the GCP project.

> You can find the official documentation to create GCP project [here](https://developers.google.com/maps/gmp-get-started#procedures).

## Adding Google Maps SDK
To use Google Maps plugin, we need to add `Maps SDK` for both Android & iOS. To add the required SDK, follow the below steps.
1. Go to `APIs & Services` from the Navigation menu and select `Library`.
![APIs & Services](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iegssedppriahqyykrue.png)
2. Search for `Maps` and enable `Maps SDK` for both Android & iOS.
![SDK](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9twdbs85het5j8qf25ur.png)

With this, we have added the required Maps SDK.

## Creating an API key
At last, we need an API key to connect our Flutter application with this GCP project. To create an API key, follow the below steps.
1. Go to `APIs & Services` from the Navigation menu and select `Credentials`.
![APIs & Services](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8idct3m7orqd4h2wjme.png)
2. Click `CREATE CREDENTIALS` and select `API key`.
![Credentials](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d493sz07qc5rjqqgi769.png)

With this, we have created the API key that we will be using later in the flutter application.

## Setting up Flutter application
Create a new Flutter project and open it in favorite IDE.
```
flutter create fluttermap
```

Go to `pubspec.yaml` file and add [google_maps_flutter](https://pub.dev/packages/google_maps_flutter) plugin under `dependencies` and then run `flutter pub get`.

```
dependencies:
  ...
  google_maps_flutter: ^2.1.0
```

### Android setup
Set the minSdkVersion in android/app/build.gradle.
```java
android {
    defaultConfig {
        minSdkVersion 20
    }
}
```

Go to `android/app/src/main/AndroidManifest.xml` and add the following code inside the application tag.
```xml
<meta-data android:name="com.google.android.geo.API_KEY"
           android:value="YOUR KEY HERE"/>
```

Add the following code under manifest tag.
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```

### iOS setup
Go to `ios/Runner/AppDelegate.swift` and replace the entire code with the following.
```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)
  }
}
```
Go to `ios/Runner/Info.plist` and add the following code.
```swift
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location Access.</string>
```
With this, we have completed the setup to use Google Maps plugin.

## Adding Google Maps Widget.
Let's create a base where we will add the Map.
```dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Map',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Map(),
    );
  }
}

class Map extends StatefulWidget {
  @override
  _MapState createState() => _MapState();
}

class _MapState extends State<Map> {
  @override
  Widget build(BuildContext context) {
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;

    return Container(
      height: height,
      width: width,
      child: Scaffold(
        body: Stack(
          children: <Widget>[
            // Todo: Add Map
          ],
        ),
      ),
    );
  }
}
```

We will be using `Stateful Widget` inside which we had created a `Container`. As the child of Container, we are using a `Scaffold` widget whose body is the `Stack` widget. We will keep the Map in the background and every other widget on the top of it.

We have also calculated the width and height of the screen, so that the Map can cover it entirely.

Now, let's add the Google Map widget.
```dart
// import package
import 'package:google_maps_flutter/google_maps_flutter.dart';

// set an initial location of the Map
CameraPosition _initialCameraPosition = CameraPosition(target: LatLng(20.5937, 78.9629));

// add this to control the Map
GoogleMapController googleMapController;

// Replace "Todo: Add Map" with the following
GoogleMap(
  initialCameraPosition: _initialCameraPosition ,
  myLocationEnabled: true,
  myLocationButtonEnabled: true,
  mapType: MapType.normal,
  zoomGesturesEnabled: true,
  zoomControlsEnabled: true,
  onMapCreated: (GoogleMapController c) {
    // to control the camera position of the map
    googleMapController = c;
  },
),
```
Let’s explore the parameters that are used in the Google Maps widget.
* **initialCameraPosition**: To load the map view on initial start up. It's a required parameter.
* **myLocationEnabled**: To show current location on the map with a blue dot.
* **myLocationButtonEnabled**: To bring the user location to the center of the map.
* **mapType**: To specify the displayed map type. Possible values are normal, satellite, hybrid and terrain.
* **zoomGesturesEnabled**: To determine whether the map should respond to zoom gestures.
* **zoomControlsEnabled**: To show zoom controls.
* **onMapCreated**: A callback function that gets executed when the map is ready.

With this, we have added the Google Map Widget in our Flutter Application. On running the application the output should look like this.

![output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s951kf20m0vlecvwhgp4.png)

Thanks for the read. I hope this article helped you to get started with Google Maps in Flutter.

You can connect with me on [Twitter](https://twitter.com/shubhHAM_) for any discussion.

Happy Coding!