DEV Community

loading...
Cover image for  How to Add Google Maps in Flutter

How to Add Google Maps in Flutter

kris
React native developer and Technical writer Americano addicted
Originally published at instaflutter.com ・7 min read

The Flutter ecosystem is flourishing and will definitely make a huge mark in the near future as one of the most established cross-platform mobile application development frameworks. The community is rapidly growing and there are already many powerful libraries available already. In this tutorial, we are going to make use of the googler_maps_flutter package in order to display maps in our Flutter apps.

Maps are used in applications that deal with navigation and delivery such as Yelp or UberEats, shopping applications, geolocation apps, etc. We can use it to show locations, track locations, real-time navigation, etc. In this tutorial, we are going to use the Google Maps API from the Google Developer Console. The idea is to integrate the Google API key equipped with Android Google map SDK to our Flutter project. Then, we will use the mentioned package to show the map on the app screen. We will also work with markers and their customizations.

So, let’s get started!

Create a New Flutter Project

First, we need to create a new Flutter project. For that, make sure that the Flutter SDK and other Flutter app development-related requirements are properly installed. If everything is properly set up, then in order to create a project, we can simply run the following command in the desired local directory:

flutter create googleMapExample
Enter fullscreen mode Exit fullscreen mode

After the project has been set up, we can navigate inside the project directory and execute the following command in the terminal to run the project in either an available emulator or an actual device:

flutter run
Enter fullscreen mode Exit fullscreen mode

After successfully build, we will get the following result in the emulator screen:

Scaffolding the Flutter Project

Now, we need to replace the default template with our own project structure template. First, we need to create a folder called ./screens inside the ./lib folder. Then, inside the ./lib/screens folder, we need to create a new file called Home.dart. Inside the Home.dart, we are going to implement a simple Stateful widget class returning a Scaffold widget with a basic App bar and an empty Container body. The code for Home.dart is shown in the code snippet below:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Maps"),
        centerTitle: true,
      ),
      body: Container(
        child: Center(
          child: Text("Maps"),
        ),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Now, we need to replace the default template in the main.dart file and call the HomePage screen in the home option of MaterialApp widget as shown in the code snippet below:

import 'package:flutter/material.dart';
import 'package:mapExample/screens/Home.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: HomePage(),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Hence, we will get the screen as shown in the screenshot below:

Getting The API Key for Google Maps

Now, we need the API key for Google Maps in order to access the map in our application. The process to get the API key is easy. We need to go on and login to Google Developer Console at https://cloud.google.com/maps-platform.

In the developer console, we need to create a project if we don’t have one already, which will lead us to the following screen:

In the above screenshot, we are in the Credentials view of our project. In Credentials, we can create the API key and restrict it for the particular service which in our case is Android Google Maps SDK.

When we click on “+ CREATE CREDENTIALS”, we will get the options as shown in the screenshot below:

From the options, we need to click on “API key”, which will lead us to follow dialog:

The dialog states that the API key is created. It means we have the API key now but the services to be provided by the API key are yet not enabled.

Hence, we will get the API key without any service as shown in the code snippet below:

Since our API key is not restricted to any services, we need to apply some restrictions to it. But before that, we need to ensure that the “ Google Maps Android API v2 “ service is enabled.

Then, we can restrict the API key to Maps SDK for Android by navigating inside API key1 as shown in the screenshot below:

After selecting the service that we require, we need to click on ‘SAVE’ to save the configurations to the API key.

Then, we will get the API key with Google Maps SDK for Android enabled as shown in the screenshot below:

Now, our API key is enabled and ready for use.

Adding the API Key to our Flutter App

In order to add the Android Maps API key to the Flutter project, we need to first go to the AndroidManifest.xml file.

In our AndroidManifest.xml file, we need to add the following code as a child of the application element:

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

Here, we need to replace the value in android:value with the API key that we generated in the above steps.

Make sure you use your own API key.

Installing Google Maps Flutter Plugin

Now, we are going to use the package called google_maps_flutter. This plugin provides the GoogleMap widget to be used in our Flutter project to show the map on the screen. The widget houses many properties that allow us to tamper with the displayed map and customize it accordingly.

Now, to install this plugin, we need to add the plugin in our pubspec.yaml file as shown in the code snippet below:

dependencies: 
     google_maps_flutter: ^1.2.0
Enter fullscreen mode Exit fullscreen mode

Adding Maps to The Home Screen

Now, we are going to add the GoogleMap widget to our Home screen to display the map on the screen. For this, we need to initialize the GoogleMapController that handles the loading state of the map. Then, we need to define the CameraPosition that determines which location the map has to show in. In CameraPosition class, we can assign the target value which is latitude and longitude. We can also specify the zoom value which will determine how much the camera is to be zoomed into the map.

Then, we need to use the GoogleMap widget with all the required properties configured as shown in the code snippet below:

class _HomePageState extends State<HomePage> {
  Completer<GoogleMapController> _controller = Completer();

  static final CameraPosition _initialCameraPosition = CameraPosition(
    target: LatLng(37.42796133580664, -122.085749655962),
    zoom: 15,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Maps"),
        centerTitle: true,
      ),
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: _initialCameraPosition,
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Here, using the mapType option on the GoogleMap widget, we can choose what type of map to show. It can be a satellite image, a roadmap, or a normal map. The onMapCreated event will be created after the map has been placed on the screen. In this event, we can choose to add the map markers which we are going to do later.

The resultant map is shown in the screenshot below:

Adding Map Markers

Now, we are going to add a marker to our map. The markers help us show a specific location on the map. In order to set the markers, we need to initialize a state that holds the markers. Then, we are going to create a function that will be triggered in the onMapCreated event. After the map is created, we will add the markers to the screen. To add markers, we have access to the Marker widget which will take a markerId and position value (latitude and longitude). The markers initialization is provided in the code snippet below:

Set<Marker> _markers = {};

void _onMapCreated (GoogleMapController controller) {
  setState(() {
    _markers.add(
      Marker(
        markerId: MarkerId("id-1"),
        position: LatLng(37.42796133580664, -122.085749655962)
      )
    );
  });
}
Enter fullscreen mode Exit fullscreen mode

Now, we need to set the markers property in GoogleMap widget and also assign the _onMapCreated function in the onMapCreated event as shown in the code snippet below:

body: GoogleMap(
  mapType: MapType.normal,
  initialCameraPosition: _initialCameraPosition,
  onMapCreated: _onMapCreated,
  markers: _markers,
),
Enter fullscreen mode Exit fullscreen mode

Hence, we will get the marker on the map as shown in the screenshot below:

Adding Info to The Map Markers

We can also customize our markers based on our own needs. We can add information to it as well. The information will be shown once we click on the marker on the map. In order to add the marker info, we need to add infoWindow property to the Marker widget. Then, we need to use the InfoWindow widget to add extra information to the marker as shown in the code snippet below:

void _onMapCreated (GoogleMapController controller) {
    setState(() {
      _markers.add(
        Marker(
          markerId: MarkerId("id-1"),
          position: LatLng(37.42796133580664, -122.085749655962),
          infoWindow: InfoWindow(
            title: "GooglePlex"
          )
        )
      );
    });
  }
Enter fullscreen mode Exit fullscreen mode

Now once we click on the marker, we will see the information as shown in the screenshot below:

Not only that, we can add custom icons and other elements to the marker which is pretty easy as well.

Finally, we have successfully integrated Google Maps into our Flutter map project using Google Maps SDK API key from Google Developer Console and google_maps_flutter package.

Conclusion

The main objective of this Flutter tutorial is to explore the integration of Google Maps in the Flutter environment. Google Maps is a powerful geo-navigation service provided by Google which can be integrated into almost any technology nowadays. In this case, we made use of Google API restricted to Android Google Maps SDK to integrate Google Maps into our Flutter project.

Then, in order to show the actual map on the UI of the mobile app, we made use of the latest package available which is google_maps_flutter. The configurations were easy and simple. The map was set up with the help of a simple GoogleMap widget and some basic configurations. In the end, we were also able to add some markers to the map. A lot of other things are possible with this widget which is a challenge for you to explore.

If you found this tutorial on how to add maps to Flutter apps, please consider spreading the word, by sharing the link further. Cheers!

Originally published at https://www.instaflutter.com on March 3, 2021.

Discussion (1)

Collapse
pablonax profile image
Pablo Discobar

If you are interested in this topic, you can also look at my article about paid Flutter templates. I'm sure you'll find something useful there, too.  dev.to/pablonax/flutter-mobile-app...