Creating Google Maps API Key
To Display Google Map, we must need API Key.
Step 1:
Step 2: Enable Service
We require
- Maps SDK for Android
- Maps SDK for iOS
Step 3: Create API Key & copy it
Adding Google Maps Flutter plugin as a dependency
Adding additional capability to a Flutter app is easy using Pub packages. In this article you introduce the Google Maps Flutter plugin by running the following command from the project directory.
To get the latest version of the Google Maps SDK on iOS requires a platform minimum version of iOS 11. Modify the ios/Podfile as follows.
# Set platform to 11.0 to enable latest Google Maps SDK
platform :ios, '11.0' # Uncomment and set to 11.
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
Configuring Android minSDK
To use Google Maps SDK on Android requires setting the minSDK
to 20. Modify the android/app/build.gradle as follows.
android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.google_maps_in_flutter"
minSdkVersion 20 // Update from 16 to 20
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
}
Adding an API key for an Android app
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 inside the application
node.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google_maps_in_flutter">
<application
android:label="google_maps_in_flutter"
android:icon="@mipmap/ic_launcher">
<!-- TODO: Add your Google Maps API key here -->
<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|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
Adding an API key for an iOS app
To add an API key to the iOS app, edit the AppDelegate.swift
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.
ios/Runner/AppDelegate.swift
import UIKit
import Flutter
import GoogleMaps // Add this import
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
// TODO: Add your Google Maps API key
GMSServices.provideAPIKey("YOUR-API-KEY")
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
Putting a map on the screen
Now it's time to get a map on the screen. Update lib/main.dart
as follows:.
lib/main.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late 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: const Text('Maps Sample App'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
),
);
}
}
Running the app
Run the Flutter app in either iOS or Android to see a single map view, centered on Portland. Alternatively, run up either an Android emulator or an iOS simulator. Feel free to modify the map center to represent your hometown, or somewhere that is important to you.
Put Google on the Map
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. In this step, you will use code generation to parse JSON.
Add three new Flutter dependencies to the project as follows. Firstly, add the http
package for making HTTP requests easily.
Next, add json_serializable for declaring object structure for representing JSON documents.
Finally, add build_runner as a development time dependency. This will be used for code generation later in this step.
Parsing JSON with code generation
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.
In the lib/src
directory, create a locations.dart
file and describe the structure of the returned JSON data as follows:
lib/src/locations.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
import 'package:flutter/services.dart' show rootBundle;
part 'locations.g.dart';
@JsonSerializable()
class LatLng {
LatLng({
required this.lat,
required 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({
required this.coords,
required this.id,
required this.name,
required 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({
required this.address,
required this.id,
required this.image,
required this.lat,
required this.lng,
required this.name,
required this.phone,
required 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({
required this.offices,
required 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
try {
final response = await http.get(Uri.parse(googleLocationsURL));
if (response.statusCode == 200) {
return Locations.fromJson(json.decode(response.body));
}
} catch (e) {
print(e);
}
// Fallback for when the above HTTP request fails.
return Locations.fromJson(
json.decode(
await rootBundle.loadString('assets/locations.json'),
),
);
}
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
Your code should now analyze cleanly again. Next, we should add in the fallback locations.json file used in the getGoogleOffices
function. One of the reasons for including this fallback is that the static data being loaded in this function is served without CORS headers, and thus will fail to load in a web browser. The Android and iOS Flutter apps don't need CORS headers, but mobile data access can be finicky at the best of times.
Navigate to https://about.google/static/data/locations.json
in your browser, and save the contents into the asset directory. Alternatively, you can use the command line as follows.
Now that you have the asset file downloaded, add it to the flutter section of your pubspec.yaml
file.
pubspec.yaml
flutter:
uses-material-design: true
assets:
- assets/locations.json
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(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@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) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Google Office Locations'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: const CameraPosition(
target: LatLng(0, 0),
zoom: 2,
),
markers: _markers.values.toSet(),
),
),
);
}
}
This code performs several operations:
- In
_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.
- The markers are stored in a
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.
Congratulations!
You have completed