Introduction
Google Maps is a powerful tool that can enhance your Flutter applications by providing rich, interactive maps. Whether you’re building an app that requires location tracking, route planning, or simply displaying a map, integrating Google Maps into your Flutter app is a great choice. This guide will walk you through the steps to add Google Maps to your Flutter application.
Table of Contents
- Prerequisites
- Setting Up Your Flutter Project
- Adding the Google Maps Plugin
- Configuring the Android App
- Configuring the iOS App
- Displaying Google Maps
- Customizing the Map
- Handling Map Events
- Best Practices
- Conclusion
Prerequisites
Before you start, ensure you have the following:
- A Google Cloud Platform (GCP) project with the Google Maps SDK for Android and iOS enabled.
- A Google Maps API key.
- Flutter installed on your development machine.
Setting Up Your Flutter Project
- Create a New Flutter ProjectbashCopy code
flutter create google_maps_example cd google_maps_example
- Open the Project in Your IDE
- Use your preferred IDE (e.g., Visual Studio Code, Android Studio) to open the project.
Adding the Google Maps Plugin
Add the google_maps_flutter
plugin to your pubspec.yaml
file:
yamlCopy codedependencies:
flutter:
sdk: flutter
google_maps_flutter: ^2.0.6
Run flutter pub get
to install the plugin.
Configuring the Android App
- Add the Google Maps API KeyOpen the
android/app/src/main/AndroidManifest.xml
file and add your API key within the<application>
tag:xmlCopy code<manifest> <application> <!-- Add this meta-data tag --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY"/> </application> </manifest>
- Update
android/app/build.gradle
Ensure that yourminSdkVersion
is set to at least 20:groovyCopy codeandroid { ... defaultConfig { ... minSdkVersion 20 } }
Configuring the iOS App
- Add the Google Maps API KeyOpen the
ios/Runner/AppDelegate.swift
file and add the following code to set the API key:swiftCopy codeimport UIKit import Flutter import GoogleMaps @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GMSServices.provideAPIKey("YOUR_API_KEY") GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
- Update
ios/Podfile
Ensure the platform is set to at least iOS 9.0:rubyCopy codeplatform :ios, '9.0'
- Install CocoaPods DependenciesRun the following command in the
ios
directory:bashCopy codepod install
Displaying Google Maps
- Create a StatefulWidgetIn your
lib/main.dart
file, create a StatefulWidget to display the map:dartCopy codeimport 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Google Maps Demo', home: MapSample(), ); } } class MapSample extends StatefulWidget { @override State<MapSample> createState() => MapSampleState(); } class MapSampleState extends State<MapSample> { late GoogleMapController mapController; final LatLng _center = const LatLng(37.7749, -122.4194); void _onMapCreated(GoogleMapController controller) { mapController = controller; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Google Maps Demo'), backgroundColor: Colors.green[700], ), body: GoogleMap( onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition( target: _center, zoom: 11.0, ), ), ); } }
- Run the AppRun the app on an Android or iOS emulator or a physical device:bashCopy code
flutter run
Customizing the Map
You can customize the map by adding markers, changing the map type, and more.
Adding a Marker
dartCopy codeSet<Marker> _markers = {};
void _onMapCreated(GoogleMapController controller) {
setState(() {
_markers.add(
Marker(
markerId: MarkerId('id-1'),
position: _center,
infoWindow: InfoWindow(
title: 'San Francisco',
snippet: 'An interesting city',
),
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Maps Demo'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
markers: _markers,
),
);
}
Changing the Map Type
dartCopy codeMapType _currentMapType = MapType.normal;
void _onMapTypeButtonPressed() {
setState(() {
_currentMapType = _currentMapType == MapType.normal
? MapType.satellite
: MapType.normal;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Maps Demo'),
backgroundColor: Colors.green[700],
),
body: Stack(
children: [
GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
mapType: _currentMapType,
markers: _markers,
),
Padding(
padding: EdgeInsets.all(16.0),
child: Align(
alignment: Alignment.topRight,
child: FloatingActionButton(
onPressed: _onMapTypeButtonPressed,
materialTapTargetSize: MaterialTapTargetSize.padded,
backgroundColor: Colors.green,
child: const Icon(Icons.map, size: 36.0),
),
),
),
],
),
);
}
Handling Map Events
You can handle various map events such as taps, camera movements, and more.
Handling Map Tap
dartCopy codevoid _onMapTapped(LatLng location) {
setState(() {
_markers.add(
Marker(
markerId: MarkerId(location.toString()),
position: location,
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Google Maps Demo'),
backgroundColor: Colors.green[700],
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
markers: _markers,
onTap: _onMapTapped,
),
);
}
Best Practices
- API Key Security: Do not expose your API key in the source code. Use environment variables or secure storage solutions.
- Testing: Test your app on multiple devices and screen sizes to ensure a consistent user experience.
- Permissions: Ensure your app requests the necessary location permissions and handles scenarios where permissions are denied.
Conclusion
Integrating Google Maps into your Flutter app enhances its functionality and provides users with interactive map features. By following this guide, you can easily set up and customize Google Maps in your Flutter applications. Experiment with different map types, markers, and events to create a rich user experience. Happy coding!