Flutter Beta

Learn cross-platform development with our collection of trusted high-quality Flutter tutorials!

Google Maps for Flutter Tutorial: Getting Started

In this tutorial, you’ll learn how to integrate the Google Maps API into your Flutter app by creating an app to show places to eat nearby.

4.5/5 2 Ratings

Version

  • Dart 2, Flutter 1.7, Android Studio 3.5

Location-aware services are being integrated into your life almost every day through mobile applications. Implementing these services in your apps can be done through the use of the Google Maps API. It allows you to display a map, customize its attributes and render markers of places at their geo-location among other things.

In this Google Maps for Flutter tutorial, you will build an application using Flutter and Dart to show places to eat nearby using the Google Maps API and plugin for Flutter.

Although Google Maps has been around for some time, the plugin uses Flutter’s new embedding mechanism for views which is in developer pre-release, so this plugin should be considered a pre-release as well. Check back here for updates.

Getting Started

To start, download the starter project using the Download Materials button at the top or bottom of this tutorial. Open it in Visual Studio Code, Android Studio, or your favorite editor, and build the project. You can run it on an Android emulator, but you won’t see much yet:

Empty screen

You’ll get the app running on iOS a bit later.

Take a look around the project to get familiar with the files you will be working with. Make note of the lib folder files:

  1. main.dart – loads the main application.
  2. places_search_map.dart – provides the nearby places search.
  3. search_filter.dart – provides a type filter for nearby places search.

These will be the files you will be most closely working in this project.

Also, notice with Flutter there are android and ios folders which you will need to familiarize yourself with, as this is where you will need to configure each platform for the Google Maps API. More on this in a bit.

Note: This tutorial assumes prior knowledge of Dart and the Flutter framework for developing cross-platform mobile apps. If you are unfamiliar with Flutter, please see Getting Started with Flutter to get yourself familiar with Flutter application development. This tutorial also assumes some prior knowledge of mobile application development on iOS and Android. You do not, however, need to be an expert in either area as you will only need to do minimal setup per platform.

Without further adieu, time to get started.

Creating API Keys

In order to get started with Google Maps you first need to create an API key for your new project. To create an API key navigate to the Google Maps and click GET STARTED to step through the wizard to set up your API key.

On the following screens you need to:

  1. Enable Google Maps API.
  2. Create a new project called Flutter Maps.
  3. Choose a billing account (don’t worry there is a free tier to use).
Maps API Key wizard

Maps API Key wizard

Once, you have successfully created your API key make sure to copy it and save it someplace, as you will need to add it into your Flutter app.

Adding the Google Maps Plugin

To get started using Google Maps Plugin open the pubspec.yaml file and under dev_dependencies paste the following, using the same indentation as flutter_test::

google_maps_flutter:

Be sure to run Packages get after you make this change.

Android Setup

Next, open android ‣ app ‣ src ‣ main ‣ AndroidManifest.xml and paste the Google Maps meta data tag into your application tag before the activity tag, placing the API key you copied before to replace {{YOUR_API_KEY_HERE}}.

<meta-data android:name="com.google.android.geo.API_KEY" 
   android:value="{{YOUR_API_KEY_HERE}}"/>
Note: For the value field, please paste in your API Key from the Google Maps API registration process.

Here, you register the API in the manifest for your Android app.

iOS Setup

Next, open the ios ‣ Runner ‣ AppDelegate.m file and paste the following code before the comment and return statement.

[GeneratedPluginRegistrant registerWithRegistry:self];
[GMSServices provideAPIKey:@"{{YOUR_API_KEY_HERE}}"];
Note: Again, for the value field please paste in your API Key from the registration process.

This registers your API key for your iOS version of the Flutter project.

Finally, open up ios ‣ Runner ‣ Info.plist and paste in the following key value pair inside the dict tag:

<key>io.flutter.embedded_views_preview</key>
<string>YES</string>

Here you opt-in to embedded views preview for iOS. This is required in order to use Google Maps for Flutter on iOS.

Now, you are ready to add Google Maps into your application.

Adding the GoogleMap Widget

Open lib ‣ places_search_map.dart and add these two member variables to _PlacesSearchMapSample, resolving the imports with package:google_maps_flutter/google_maps_flutter.dart:

// 1
Completer<GoogleMapController> _controller = Completer();
// 2
static final CameraPosition _myLocation =
  CameraPosition(target: LatLng(0, 0),);

Here you have:

  1. Defined the callback for the completion of creating the map.
  2. Created the map’s initial camera position (where to focus on the map).

Then, replace the contents of the build() method with the following code:

return Scaffold(
  // 1
  body: GoogleMap(
    // 2
    initialCameraPosition: _myLocation,
    // 3
    mapType: MapType.normal,
    // 4
    onMapCreated: (GoogleMapController controller) {
      _controller.complete(controller);
    },
  ),
);

Here you have:

  1. Included the GoogleMap widget as the body of your Scaffold widget.
  2. Set the initial camera position
  3. Set the mapType to normal.
  4. Added a callback to listen for the creation of the Map widget.

Finally run your app using the normal means in your IDE, or by typing the following command into the terminal in the project root:

flutter run
Maps on Flutter

Maps on Flutter

You can also now run the app on iOS:

Maps on iOS

Maps on iOS

Great! You now have a functioning map. Time to customize it to make it a bit more interesting.

Customizing the Map

The Google Maps widget can be customized in various ways so that it can both look great in your applications and function for your specific use case. You can alter the camera’s position (view and orientation of the map), the type of map (hybrid, satellite, etc.) and add markers and overlays.

Camera Position Attributes

To customize the location and view point of the map you can alter attributes of intitialCameraPosition the CameraPosition for the GoogleMap widget.

It allows you to set:

  1. target: The latitude and longitude of where to center the map.
  2. bearing: The direction the camera faces (north, south, east, west, etc.).
  3. tilt: The angle the camera points to the center location.
  4. zoom: The magnification level of the camera position on the map.

Update the _myLocation class member variable you previously defined in the _PlacesSearchMapSample class to include a zoom of 12, and update the target to take advantage of the class members, latitude and longitude. It should now look like this:

  static final CameraPosition _myLocation = CameraPosition(
    // 1
    target: LatLng(latitude, longitude),
    // 2
    zoom: 12,
  );

In these changes you:

  1. Specified a target position for the camera in latitude and longitude.
  2. Added a zoom level of the camera at 12.

Re-run the app to see the changed starting location and zoom. You may need to close and open the app to see the changes throughout this tutorial.

app screenshot with map centered on Manhattan

Maps display

Finally, add the bearing and tilt values to customize the camera position some more.

Add these two values to the _myLocation member variable:

bearing: 15.0, // 1
tilt: 75.0, // 2

Here you have:

  1. Pointed the camera with a bearing of 15 degrees.
  2. Added a tilt to the camera at a 75 degree angle.
Map with bearing and tilt

Map with bearing and tilt

Note: changing the zoom level will affect the tilt of the camera.

Map Types

The GoogleMap attribute mapType allows you to customize the tiles within the map. The current supported types are:

  1. normal: Normal tiles (traffic and labels, subtle terrain information).
  2. satellite: Satellite imaging tiles (aerial photos).
  3. terrain: Terrain tiles (indicates type and height of terrain).
  4. hybrid: Hybrid tiles (satellite images with some labels/overlays).

You’ll stick with normal tiles in this tutorial, but feel free to experiment with mapType if you wish.

Styling the map

Google Maps can be customized to provide a limited set of display features such as landmarks, roads, and other built-up areas. You do this by providing a JSON file that specifies these customizations. Head over to Styling a Google Map iOS to view the options for iOS and head over to Style a Google Map Androd to see the same for Android.

Note: Be sure check the features are supported on both map types.

To add a style to your map copy the following method into the _PlacesSearchMapSample class:

  void _setStyle(GoogleMapController controller) async {
    String value = await DefaultAssetBundle.of(context)
                           .loadString('assets/maps_style.json');
    controller.setMapStyle(value);
  }

Here, you load a JSON file with the customizations and apply them to the map. You can open maps_style.json in the project assets folder to see what changes are specified.

Then, add a call to your new method in your GoogleMap widget by adding it to the onMapCreated argument anonymous function just before _controller.complete(controller);:

_setStyle(controller);

Here you have called the _setStyle() method passing in the GoogleMapController to set the style of the Google map. If you want to configure a different style, replace the maps_style.json in the assets folder with a style from the Maps Style generator.

Run the app again to see your new customizations.

Styled map

Styled map

Places Search Restful API

So this is pretty cool to display a GoogleMap widget, but it isn’t all that useful without adding some places to explore on the map. The widget allows you to do this by using the Places API and adding map Markers.

To get started, first head back over to the Google Maps API Console and enable the places API feature for your project. Make sure your Flutter Maps project is selected at the top before clicking Enable.

Enable places API

Enable places API

Once, it is done find and copy your same API key as before. Open places_search_map.dart and back in the _PlacesSearchMapSample class, replace the value of the _API_KEY variable with your API Key:

static const String _API_KEY = '{{YOUR_API_KEY_HERE}}';

You can now use the API key to interact with the Places API!

Next, add the following member variable to the _PlacesSearchMapSample class:

List<Marker> markers = <Marker>[];

This allows you to store and display the markers you’ll create later.

Then, create the searchNearby() function by adding the following code to your _PlacesSearchMapSample class. Make sure you import 'dart:convert' and 'package:http/http.dart' as http, which should already be in the starter project:

// 1
void searchNearby(double latitude, double longitude) async {
  setState(() {
    markers.clear(); // 2
  });
  // 3
  String url =
      '$baseUrl?key=$_API_KEY&location=$latitude,$longitude&radius=10000&keyword=${widget.keyword}';
  print(url);
  // 4
  final response = await http.get(url);
  // 5
  if (response.statusCode == 200) {
    final data = json.decode(response.body);
    _handleResponse(data);
  } else {
    throw Exception('An error occurred getting places nearby');
  }
  setState(() {
    searching = false; // 6
  });
}

Here you have:

  1. Added the search function.
  2. Provided a way to clear existing markers.
  3. Set the REST URL up to perform the request.
  4. Made an HTTP GET request to the REST endpoint.
  5. Parsed the response into model data.
  6. Set the searching flag to false.

Next, you want to add a floating action button to perform the places search:

In the same class, _PlacesSearchMapSample, in your Scaffold widget add the floatingActionButton:

// 1
floatingActionButton: FloatingActionButton.extended(
  onPressed: () {
    searchNearby(latitude, longitude); // 2
  },
  label: Text('Places Nearby'), // 3
  icon: Icon(Icons.place), // 4
),

Here you have:

  1. Added the FloatingActionButton to your Scaffold widget.
  2. Provided the function to search nearby using latitude and longitude.
  3. Added a label for the button.
  4. Added an icon for the button.

Run the app to see your new button. Nothing will happen when you click it yet, but that is next.

Styled map with floating action button

Styled map with floating action button

Great job! Now you need to actually create the markers to display on the map!

Showing Map Markers for Search Results

First, navigate to the _handleResponse(data) method and paste in the following code inside the else if block checking data[status] == "OK". Use 'data/place_response.dart' for the required import:

// 1
setState(() {
  // 2
  places = PlaceResponse.parseResults(data['results']);
  // 3
  for (int i = 0; i < places.length; i++) {
    // 4
    markers.add(
      Marker(
        markerId: MarkerId(places[i].placeId),
        position: LatLng(places[i].geometry.location.lat,
            places[i].geometry.location.long),
        infoWindow: InfoWindow(
            title: places[i].name, snippet: places[i].vicinity),
        onTap: () {},
      ),
    );
  }
});

Here you have:

  1. Set the state in the Statefulwidget.
  2. Parsed the places results into a list.
  3. Looped over the places response list.
  4. Added a map Marker for each entry in the places list.

To complete the setup, add the markers attribute inside your GoogleMap widget following the onMapCreated attribute:

markers: Set<Marker>.of(markers),

Here you have specified the markers attribute of the GoogleMap widget.

Now you can run your app, press the Places Nearby button, and see some nearby places!

Map Markers on a styled map

Map Markers on a styled map

Congratulations on completing a full Google Maps app in Flutter!

Where to Go From Here?

You can download the final project using the Download Materials button at the top or bottom of this tutorial. If you had trouble following along, run and install the finished version of the application.

Browse around the finished project to see the code all at once. Make sure to add your API key to places_search_map.dart, AndroidManifest.xml and AppDelegate.m as explained in the tutorial before you try to run it!

Google Maps are a lot of fun to work with and can provide useful features for your application's users. To enhance the application, instead of passing in a fixed latitude and longitude, try accessing the device's current location and passing that into the search request.

You can learn more about what you can do by looking at the GitHub for Google Maps for Flutter and the deleloper page for Google Maps.

I hope you enjoyed this tutorial on Google Maps with Flutter! Thanks for reading and if you have any questions or comments, please leave a rating and join the forum discussion below.

Average Rating

4.5/5

Add a rating for this content

2 ratings

Contributors

Comments