Displaying Maps and Adding Markers Using the google_maps_flutter Package in Flutter

Flutter, Google’s UI toolkit, has revolutionized cross-platform mobile app development, enabling developers to write code once and deploy it on multiple platforms. When building location-based apps, displaying maps and adding markers are essential features. The google_maps_flutter package in Flutter provides an easy way to integrate Google Maps into your applications.

What is the google_maps_flutter Package?

The google_maps_flutter package is a Flutter plugin that allows you to display interactive Google Maps in your Flutter app. It offers various functionalities, including:

  • Displaying maps with customizable options.
  • Adding markers, polylines, and polygons to the map.
  • Handling map gestures like zooming and panning.
  • Controlling the camera position and zoom level programmatically.

Why Use Google Maps in Flutter?

  • Cross-Platform: Integrates seamlessly across Android and iOS.
  • Feature-Rich: Supports markers, polylines, polygons, and custom styling.
  • Easy to Use: Straightforward APIs for quick implementation.
  • Performance: Optimized for smooth and responsive map interactions.

How to Display Maps and Add Markers in Flutter Using google_maps_flutter

Follow these steps to implement Google Maps with markers in your Flutter app:

Step 1: Set Up Your Flutter Project

If you don’t have a Flutter project, create a new one using the Flutter CLI:

flutter create google_maps_example

Step 2: Add the google_maps_flutter Package

Add the google_maps_flutter dependency to your pubspec.yaml file:

dependencies:
 google_maps_flutter: ^2.2.6

Then, run:

flutter pub get

Step 3: Configure API Keys for Android and iOS

To use Google Maps, you need API keys for both Android and iOS. Get your API keys from the Google Cloud Console.

Android Configuration
  1. Add API Key to AndroidManifest.xml

    Open android/app/src/main/AndroidManifest.xml and add the following meta-data tag inside the <application> tag:

    <meta-data
     android:name="com.google.android.geo.API_KEY"
     android:value="YOUR_ANDROID_API_KEY"/>
  2. Set Min SDK Version

    Ensure your android/app/build.gradle file has a minSdkVersion of at least 20:

    android {
     defaultConfig {
     minSdkVersion 20
     ...
     }
     }
  3. Enable Required APIs in Google Cloud Console

    Make sure to enable the “Maps SDK for Android” API in your Google Cloud Console.

iOS Configuration
  1. Add API Key to AppDelegate.swift or AppDelegate.m

    For Swift, open ios/Runner/AppDelegate.swift and add the following import and key setup:

    import UIKit
    import Flutter
    import GoogleMaps
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
     override func application(
      _ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
     ) -> Bool {
      GMSServices.provideAPIKey("YOUR_IOS_API_KEY")
      GeneratedPluginRegistrant.register(with: self)
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
     }
    }

    For Objective-C, open ios/Runner/AppDelegate.m and add the following import and key setup:

    #import <Flutter/Flutter.h>
    #import <UIKit/UIKit.h>
    #import <GoogleMaps/GoogleMaps.h>
    
    @implementation AppDelegate
    - (BOOL)application:(UIApplication *)application
     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     [GMSServices provideAPIKey:@"YOUR_IOS_API_KEY"];
     [GeneratedPluginRegistrant registerWithRegistry:self];
     return [super application:application didFinishLaunchingWithOptions:launchOptions];
    }
    @end
  2. Enable Required APIs in Google Cloud Console

    Make sure to enable the “Maps SDK for iOS” API in your Google Cloud Console.

Step 4: Implement the Map Widget

Replace the contents of lib/main.dart with the following code:

import '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: 'Flutter Google Maps Demo',
      home: MapScreen(),
    );
  }
}

class MapScreen extends StatefulWidget {
  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
  late GoogleMapController mapController;
  
  final LatLng _center = const LatLng(45.521563, -122.677433); // Initial map center

  final Set<Marker> _markers = {};

  @override
  void initState() {
    super.initState();
    _markers.add(Marker(
      markerId: MarkerId(_center.toString()),
      position: _center,
      infoWindow: InfoWindow(
        title: 'My Location',
        snippet: 'This is my current location',
      ),
      icon: BitmapDescriptor.defaultMarker,
    ));
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Maps in Flutter'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
        markers: _markers,
      ),
    );
  }
}

Explanation:

  • Import Necessary Packages: Includes material.dart for Flutter widgets and google_maps_flutter.dart for the Google Maps plugin.
  • Define LatLng: Creates a LatLng object representing the initial map center.
  • Create Markers: A Set<Marker> is used to hold map markers. In the initState, a marker is added to the center with a title and snippet.
  • Implement GoogleMap Widget:
    • The onMapCreated callback provides a GoogleMapController to interact with the map programmatically.
    • initialCameraPosition sets the initial view of the map.
    • markers displays the set of markers on the map.

Step 5: Add More Markers Interactively

You can add more markers by tapping on the map:

class _MapScreenState extends State<MapScreen> {
  late GoogleMapController mapController;
  
  final LatLng _center = const LatLng(45.521563, -122.677433); // Initial map center
  final Set<Marker> _markers = {};

  @override
  void initState() {
    super.initState();
    _markers.add(Marker(
      markerId: MarkerId(_center.toString()),
      position: _center,
      infoWindow: InfoWindow(
        title: 'My Location',
        snippet: 'This is my current location',
      ),
      icon: BitmapDescriptor.defaultMarker,
    ));
  }

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }
  
  void _onMapTapped(LatLng location) {
    setState(() {
      _markers.add(Marker(
        markerId: MarkerId(location.toString()),
        position: location,
        infoWindow: InfoWindow(
          title: 'New Marker',
          snippet: 'This is a new location',
        ),
        icon: BitmapDescriptor.defaultMarker,
      ));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Google Maps in Flutter'),
      ),
      body: GoogleMap(
        onMapCreated: _onMapCreated,
        initialCameraPosition: CameraPosition(
          target: _center,
          zoom: 11.0,
        ),
        markers: _markers,
        onTap: _onMapTapped, // Add this line
      ),
    );
  }
}

Conclusion

Integrating Google Maps into your Flutter app using the google_maps_flutter package is straightforward. You can display maps, add markers, and handle map interactions effectively. Ensure you configure API keys for both Android and iOS and enable the necessary APIs in the Google Cloud Console. This tutorial provides a solid foundation for building more advanced location-based features in your Flutter applications.