DEV Community

Cover image for How to add Google Maps plugin in Flutter?
Shubham Singh Kshatriya
Shubham Singh Kshatriya

Posted on

How to add Google Maps plugin in Flutter?

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 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.
  2. Open Select a project dialog and click on New Project. Project select
  3. Enter project name and click on Create. Project create

With this, we have created the GCP project.

You can find the official documentation to create GCP project here.

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
  2. Search for Maps and enable Maps SDK for both Android & iOS. SDK

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
  2. Click CREATE CREDENTIALS and select API key. Credentials

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
Enter fullscreen mode Exit fullscreen mode

Go to pubspec.yaml file and add google_maps_flutter plugin under dependencies and then run flutter pub get.

dependencies:
  ...
  google_maps_flutter: ^2.1.0
Enter fullscreen mode Exit fullscreen mode

Android setup

Set the minSdkVersion in android/app/build.gradle.

android {
    defaultConfig {
        minSdkVersion 20
    }
}
Enter fullscreen mode Exit fullscreen mode

Go to android/app/src/main/AndroidManifest.xml and add the following code inside the application tag.

<meta-data android:name="com.google.android.geo.API_KEY"
           android:value="YOUR KEY HERE"/>
Enter fullscreen mode Exit fullscreen mode

Add the following code under manifest tag.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Enter fullscreen mode Exit fullscreen mode

iOS setup

Go to ios/Runner/AppDelegate.swift and replace the entire code with the following.

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)
  }
}
Enter fullscreen mode Exit fullscreen mode

Go to ios/Runner/Info.plist and add the following code.

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location Access.</string>
Enter fullscreen mode Exit fullscreen mode

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.

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
          ],
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

// 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;
  },
),
Enter fullscreen mode Exit fullscreen mode

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

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 for any discussion.

Happy Coding!

Oldest comments (0)