Flutter is Google's mobile app SDK for crafting high-quality native experiences on iOS and Android in record time.
With the Google Maps Flutter plugin, you can add maps based on Google maps data to your application. The plugin automatically handles access to the Google Maps servers, map display, and response to user gestures such as clicks and drags. You can also add markers to your map. These objects provide additional information for map locations, and allow the user to interact with the map.
In this codelab, you'll build a mobile app featuring a Google Map using the Flutter SDK. Your app will:
|
Flutter is:
Google Maps has:
This codelab walks you through creating a Google Maps experience in a Flutter app for both iOS and Android.
This codelab focuses on adding a Google map to a Flutter app. Non-relevant concepts and code blocks are glossed over and are provided for you to simply copy and paste.
You need two pieces of software to complete this lab: the Flutter SDK, and an editor. This codelab assumes Android Studio, but you can use your preferred editor.
You can run this codelab using any of the following devices:
The easiest way to get started with Flutter is to use the flutter command line tool to create all the required code for a simple getting started experience.
$ flutter create google_maps_in_flutter Creating project google_maps_in_flutter... [Listing of created files elided] Running "flutter packages get" in google_maps_in_flutter... 6.1s Wrote 66 files. All done! [✓] Flutter (Channel dev, v1.5.0, on Mac OS X 10.14.3 18D109, locale en-AU) [✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3) [✓] iOS toolchain - develop for iOS devices (Xcode 10.2) [✓] Android Studio is fully installed. (version 3.1) [✓] IntelliJ IDEA Community Edition (version 2018.3.5) [✓] VS Code (version 1.33.1) [✓] Connected device is fully installed. (1 available) In order to run your application, type: $ cd google_maps_in_flutter $ flutter run Your application code is in google_maps_in_flutter/lib/main.dart.
Adding additional capability to a Flutter app is easy using Pub packages. In this codelab you introduce the Google Maps Flutter plugin by adding a single line to the pubspec.yaml
file.
name: google_maps_in_flutter
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.2.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# Add the following line
google_maps_flutter: ^0.5.11
flutter:
uses-material-design: true
Download the package with the following command::
$ flutter packages get Running "flutter packages get" in google_maps_in_flutter... 0.9s
To use Google Maps in your Flutter app, you need to configure an API project with the Google Maps Platform, following both the Maps SDK for Android's Get API key, and Maps SDK for iOS' Get API key processes. With API keys in hand, carry out the following steps to configure both Android and iOS applications.
To add an API key to the Android app, edit the AndroidManifest.xml
file in android/app/src/main
. Add a single meta-data entry containing the API key created in the previous step.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google_maps_in_flutter">
<application
android:name="io.flutter.app.FlutterApplication"
android:label="google_maps_in_flutter"
android:icon="@mipmap/ic_launcher">
<!-- Add the following entry, with your API key -->
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR-KEY-HERE"/>
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
To add an API key to the iOS app, edit the AppDelegate.m
file in ios/Runner
. Unlike Android, adding an API key on iOS requires changes to the source code of the Runner app. The AppDelegate is the core singleton that is part of the app initialization process.
Make two changes to this file. First, add an #import
statement to pull in the Google Maps headers, and then call the provideAPIKey()
method of the GMSServices
singleton. This API key enables Google Maps to correctly serve map tiles.
#import "AppDelegate.h"
#import "GeneratedPluginRegistrant.h"
// Add the following import.
#import "GoogleMaps/GoogleMaps.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GeneratedPluginRegistrant registerWithRegistry:self];
// Add the following line, with your API key
[GMSServices provideAPIKey: @"YOUR-API-KEY"];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end
You also need to add a setting to ios/Runner/Info.plist
. This entry forces Flutter on iOS into a single threaded mode, which is required for the platform view embedding to work. This technical restriction is being worked on and will be lifted before Google Maps moves out of Developer Preview.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- Add the following entry, from here, -->
<key>io.flutter.embedded_views_preview</key>
<true/>
<!-- to here. -->
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>google_maps_in_flutter</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
Now it's time to get a map on the screen. Update lib/main.dart
as follows:.
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
GoogleMapController mapController;
final LatLng _center = const LatLng(45.521563, -122.677433);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Maps Sample App'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
),
);
}
}
Run the Flutter app in either iOS or Android to see a single map view, centered on Portland. Feel free to modify the map center to represent your hometown, or somewhere that is important to you.
$ flutter run
When running the app in the previous step on iOS, you may have seen a warning on the console about the version of the Google Maps for iOS plugin was old. This is due to a minimum version mismatch: Flutter supports a minimum of iOS version 8, while the latest version of Google Maps SDK for iOS supports a minimum iOS version 9. The version that CocoaPods installed by default was the last version of Google Maps SDK for iOS that supports iOS version 8. In this step, you change the iOS Runner project to use the latest version of Google Maps SDK for iOS.
Please note, this step only applies to iOS, and uses Xcode to make changes to the iOS target. If you are on Windows or Linux, then this step doesn't apply to you. Please skip ahead to the next step.
Edit ios/Podfile
to declare a minimum platform version.
# Uncomment the following line
platform :ios, '9.0'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
project 'Runner', {
'Debug' => :debug,
'Profile' => :release,
'Release' => :release,
}
# And ignore the rest of this file...
Run CocoaPods to pull the up-to-date version of Google Maps SDK for iOS:
$ (cd ios && pod update) Analyzing dependencies Fetching podspec for `Flutter` from `.symlinks/flutter/ios` Fetching podspec for `google_maps_flutter` from `.symlinks/plugins/google_maps_flutter/ios` Downloading dependencies Using Flutter (1.0.0) Installing GoogleMaps 3.0.3 Using google_maps_flutter (0.0.1) Generating Pods project Integrating client project Pod installation complete! There are 2 dependencies from the Podfile and 3 total pods installed.
Configure the deployment target iOS version in the iOS Runner Xcode project so that the binary versions of the Runner and Google Maps match. Open the Runner project from the command line as follows.
$ open ios/Runner.xcworkspace/
This opens up the Xcode workspace for the iOS Runner project. Configure the Deployment Target for Runner in the General preferences pane.
Run the Flutter app in iOS, this time using the latest version of Google Maps SDK for iOS.
$ flutter run Launching lib/main.dart on iPhone XR in debug mode... Running pod install... 1.2s Running Xcode build... ├─Assembling Flutter resources... 1.3s └─Compiling, linking and signing... 4.5s Xcode build done. 7.6s Google Maps SDK for iOS version: 3.0.33124.0 Syncing files to device iPhone XR... 1,267ms 🔥 To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
Google has many offices around the world, from North America, Latin America, Europe, Asia Pacific, to Africa & Middle East. The nice thing about these maps, if you investigate them, is that they have an easily usable API endpoint for supplying the office location information in JSON format. In this step, you put these office locations on the map.
As you grow your codebase, it's time to start using tooling that Dart provides to make the code more readable and maintainable. In this step, you use code generation to parse JSON, and code linting to surface potential code smells.
To use these capabilities, add some new dependencies to the pubspec.yaml
file. These dependencies provide access to http requests, the ability to mechanize JSON parsing, a configuration of useful lint rules used widely at Google, and a build runner that ties all of it together. Edit the dependencies stanza of your pubspec.yaml
file as follows:
name: google_maps_in_flutter
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.2.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
google_maps_flutter: ^0.5.11
# Add the following two lines
http: ^0.12.0+1
json_serializable: ^2.0.2
# Add the following three lines
dev_dependencies:
pedantic: ^1.4.0
build_runner: ^1.2.7
flutter:
uses-material-design: true
Run flutter packages get
on the command line to retrieve these new dependencies, and to prepare the app for the next stages.
$ flutter packages get Running "flutter packages get" in google_maps_in_flutter... 0.5s $
Two of the nice additions to programming languages in recent years are pragmatic defaults for code formatting, and linting for known problematic code patterns. For code formatting, you can use flutter format
, although you can probably configure your code editor to run this on a certain key combination, or on file save.
$ flutter format . Formatting directory .: Unchanged test/widget_test.dart Skipping link ios/Pods/Headers/Public/google_maps_flutter/GoogleMapMarkerController.h Skipping link ios/Pods/Headers/Public/google_maps_flutter/GoogleMapController.h Skipping link ios/Pods/Headers/Public/google_maps_flutter/GoogleMapsPlugin.h Skipping link ios/Pods/Headers/Private/google_maps_flutter/GoogleMapMarkerController.h Skipping link ios/Pods/Headers/Private/google_maps_flutter/GoogleMapController.h Skipping link ios/Pods/Headers/Private/google_maps_flutter/GoogleMapsPlugin.h Skipping link ios/.symlinks/plugins/google_maps_flutter Skipping link ios/.symlinks/flutter Unchanged lib/main.dart Unchanged lib/src/locations.g.dart Unchanged lib/src/locations.dart Skipping hidden path .dart_tool $
For linting, Dart provides the ability to configure a customized code linter. In this step, you add a handful of linters to the app, but the full list of available lints is specified in the Linter for Dart documentation.
Add a file to the root of the project called analysis_options.yaml
and fill it with the following content.
include: package:pedantic/analysis_options.yaml
analyzer:
exclude:
- lib/src/locations.g.dart
linter:
rules:
- always_declare_return_types
- camel_case_types
- empty_constructor_bodies
- annotate_overrides
- avoid_init_to_null
- constant_identifier_names
- one_member_abstracts
- slash_for_doc_comments
- sort_constructors_first
- unnecessary_brace_in_string_interps
The first line includes a default set of rules used widely at Google, and the linter rules section gives a taste of what is possible. The exclude
line references a file that hasn't been generated yet. To run the lint rules, analyze the code as follows:
$ flutter analyze Analyzing google_maps_in_flutter... No issues found! (ran in 1.8s) $
If the analyzer issues warnings, don't worry, you will fix them shortly.
You might notice that the JSON data returned from the API endpoint has a regular structure. It would be handy to generate the code to marshal that data into objects that you can use in code. While Dart provides a variety of options for de-serializing JSON data (from build-it-yourself, to signing the data and using built_value
), this step uses JSON annotations.
In the lib/src
directory, create a locations.dart
file and describe the structure of the returned JSON data as follows:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
part 'locations.g.dart';
@JsonSerializable()
class LatLng {
LatLng({
this.lat,
this.lng,
});
factory LatLng.fromJson(Map<String, dynamic> json) => _$LatLngFromJson(json);
Map<String, dynamic> toJson() => _$LatLngToJson(this);
final double lat;
final double lng;
}
@JsonSerializable()
class Region {
Region({
this.coords,
this.id,
this.name,
this.zoom,
});
factory Region.fromJson(Map<String, dynamic> json) => _$RegionFromJson(json);
Map<String, dynamic> toJson() => _$RegionToJson(this);
final LatLng coords;
final String id;
final String name;
final double zoom;
}
@JsonSerializable()
class Office {
Office({
this.address,
this.id,
this.image,
this.lat,
this.lng,
this.name,
this.phone,
this.region,
});
factory Office.fromJson(Map<String, dynamic> json) => _$OfficeFromJson(json);
Map<String, dynamic> toJson() => _$OfficeToJson(this);
final String address;
final String id;
final String image;
final double lat;
final double lng;
final String name;
final String phone;
final String region;
}
@JsonSerializable()
class Locations {
Locations({
this.offices,
this.regions,
});
factory Locations.fromJson(Map<String, dynamic> json) =>
_$LocationsFromJson(json);
Map<String, dynamic> toJson() => _$LocationsToJson(this);
final List<Office> offices;
final List<Region> regions;
}
Future<Locations> getGoogleOffices() async {
const googleLocationsURL = 'https://about.google/static/data/locations.json';
// Retrieve the locations of Google offices
final response = await http.get(googleLocationsURL);
if (response.statusCode == 200) {
return Locations.fromJson(json.decode(response.body));
} else {
throw HttpException(
'Unexpected status code ${response.statusCode}:'
' ${response.reasonPhrase}',
uri: Uri.parse(googleLocationsURL));
}
}
Once you've added this code, your IDE (if you are using one) should display some red squiggles, as it references a nonexistent sibling file, locations.g.dart.
This generated file converts between untyped JSON structures and named objects. Create it by running the build_runner
:
$ flutter packages pub run build_runner build [INFO] Generating build script... [INFO] Generating build script completed, took 291ms [INFO] Initializing inputs [INFO] Reading cached asset graph... [INFO] Reading cached asset graph completed, took 65ms [INFO] Checking for updates since last build... [INFO] Checking for updates since last build completed, took 595ms [INFO] Running build... [INFO] 1.2s elapsed, 0/1 actions completed. [INFO] Running build completed, took 1.2s [INFO] Caching finalized dependency graph... [INFO] Caching finalized dependency graph completed, took 27ms [INFO] Succeeded after 1.2s with 1 outputs (1 actions) $
Your code should now analyze cleanly again.
Modify the main.dart
file to request the map data, and then use the returned info to add offices to the map:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'src/locations.dart' as locations;
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final Map<String, Marker> _markers = {};
Future<void> _onMapCreated(GoogleMapController controller) async {
final googleOffices = await locations.getGoogleOffices();
setState(() {
_markers.clear();
for (final office in googleOffices.offices) {
final marker = Marker(
markerId: MarkerId(office.name),
position: LatLng(office.lat, office.lng),
infoWindow: InfoWindow(
title: office.name,
snippet: office.address,
),
);
_markers[office.name] = marker;
}
});
}
@override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Google Office Locations'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: const LatLng(0, 0),
zoom: 2,
),
markers: _markers.values.toSet(),
),
),
);
}
This code performs several operations:
_onMapCreated
, it uses the JSON parsing code from the previous step, await
ing until it's loaded. It then uses the returned data to create Marker
s inside a setState()
callback. Once the app receives new markers, setState flags Flutter to repaint the screen, causing the office locations to display.Map
that is associated with the GoogleMap
widget. This links the markers to the correct map. You could, of course, have multiple maps and display different markers in each. Here's a screenshot of what you have accomplished. There are many interesting additions that can be made at this point. For example, you could add a list view of the offices that moves and zooms the map when the user clicks an office but, as they say, this exercise is left to the reader!
You have completed the codelab and have built a Flutter app with a Google Map! You've also interacted with a JSON Web Service.
This codelab has built an experience to visualise a number of points on a map. There are a number of mobile apps that build on this capability to serve a lot of different user needs. There are other resources that can help you take this further:
google_maps_webservice
package which makes the Google Maps Web Services, like Directions API, Distance Matrix API, and Places API really easy to use.