How to use Google Maps in Flutter

Now a days it is hard to imagine any web application or mobile application that does not use location services to provide its users the content, advertising, shopping suggestions etc. based on their current location. A lot of time you also need functionality that allows user to see locations or directions on the map. Therefore an obvious question comes to your mind is that how to use a map widget in your Flutter application. As Flutter is developed by Google Team, it already has a widget that provides Google Map widget to use in your Flutter application. Let's see how to use Google Map in your Flutter application.

Flutter has google_maps_flutter package. This has GoogleMap widget that you will use in your application. Since Google Map is going to use location and you are going to need service to track a user's location, you will also use location package in your application. To set up support for these packages in your Flutter application, you will need to add these dependencies in your pubspec.yaml file of your project.

dependencies:
  flutter:
    sdk: flutter
  
  # The following package is required to add Google Maps
  # widget in the application.
  google_maps_flutter: ^2.0.05
  # The following package adds location related functionality
  # to the application.
  location: ^4.1.1

Make sure that you have correct version of location package specified in dependencies. Do not use older version of the package if you are using Flutter 2.2 or higher. Otherwise you will end up with compile time errors like below.

Building with sound null safety 

Plugin project :location_web not found. Please update settings.gradle.  
Error: Cannot run with sound null safety, because the following dependencies
don't support null safety:

 - package:location
 - package:location_platform_interface
 - package:plugin_platform_interface

For solutions, see https://dart.dev/go/unsound-null-safety
                                                                        
                                                                        
FAILURE: Build failed with an exception.

Minimum Android API Version for Google Maps

If you look at the documentation of Google Maps SDK google_maps_flutter package, you will notice it requires minimum version of Android API to be at least 20. When you create your project in Visual Studio Code, it sets up the minimum version of Android API to be 16. If you do not change it to 20, you will see following error.

\MobileApps\byte_rx\android\app\src\main\AndroidManifest.xml Error:
        uses-sdk:minSdkVersion 16 cannot be smaller than version 20 declared in library [:google_maps_flutter] 
  \MobileApps\byte_rx\build\google_maps_flutter\intermediates\library_manifest\release\AndroidManifest.xml 
    as the library might be using APIs not available in 16
        Suggestion: use a compatible library with a minSdk of at most 16,
                or increase this project's minSdk version to at least 20,
                or use tools:overrideLibrary="io.flutter.plugins.googlemaps" to force usage (may lead to runtime failures)

Open android\app\build.gradle file in your project and update the API version. Your should have code snipper like below after this fix.

defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.mycompany.my_app"
        minSdkVersion 20
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

Set up Google Maps Key

Google Maps SDK requires an API key to use the service. You will need to register a key if you have not already done so. You can go to Google Developer Console and get started with obtaining a new key or get the one if you have already registered.

Update AndroidManifest.xml file under android\app\src folders of your project. Add your Google Maps key in this file.

<application
        android:label="byte_rx"
        android:icon="@mipmap/ic_launcher">
        <!-- Add Google Map Key -->
        <meta-data 
          android:name="com.google.android.geo.API_KEY" 
          android:value="yourgooglemapapikeyhere" />

Use GoogleMap Widget

Now you are ready to add GoogleMap widget in your Flutter application. Following is code snippet from my application that uses GoogleMap widget.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';

class RxMapView extends StatefulWidget {
  @override
  State<RxMapView> createState() => RxMapState();
}

class RxMapState extends State<RxMapView> {
  LatLng currentLocation = LatLng(0, 0);

  var location = Location();
  var markers = Set<Marker>();
  Completer<GoogleMapController> _mapController = Completer();

  @override
  void initState() {
    // Initialize location tracking.
    _getDeviceLocation();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: GoogleMap(
      mapType: MapType.hybrid,
      markers: markers,
      initialCameraPosition: CameraPosition(
        target: currentLocation,
      ),
      onMapCreated: (GoogleMapController controller) {
        _mapController.complete(controller);
      },
    ));
  }

  Future _getDeviceLocation() async {
    // If user has not consented for device to use location service
    // then any attempt to get location information will
    // throw error. Therefore we need to make sure that this part
    // of the implementation handles the error correctly.
    try {
      location.onLocationChanged.listen((newLocation) {
        print('${newLocation.longitude}: ${newLocation.latitude}');
        currentLocation =
            LatLng(newLocation.latitude ?? 0, newLocation.longitude ?? 0);
        _updateMapView();
      }, onError: (error, stackTrace) {
        print('Error: $error');
      }, onDone: () => {}, cancelOnError: false);
    } catch (ex) {
      print(ex);
    }
  }

  void _updateMapView() async {
    var controller = await _mapController.future;
    controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        bearing: 30,
        zoom: 15,
        tilt: 80)));
  }
}

This code is based on code provided with google_maps_flutter package. I will provide some explanation here.

  • Create instance of GoogleMap widget in your view hierarchy. Flutter will display the map at that location in your page or view.

  • To track location of a user, you will need to create an instance of Location object. This object provides onLocationChanged event. This event will notify your application as and when the location changes. The code snippet shows three callback functions that can get called depending on result of the action. Keep in mind that use of location service requires user's consent to allow an application to use location. If user has not consented, your application will throw error. Handle that error gracefully.

  • Google Map shows location based on camera position. You will need a state variable that keeps tracks of current location. Any time a user's location changes, you will update camera position and call animateCamera on your GoogleMapController object.

This is all you need to do to include some basic Google Map functionality in your Flutter application. I have provided lots of details about setting up compile time settings for Android application. You can look at the package document to update code under iOS folder to add support for iOS based devices.

Search

Social

Weather

19.0 °C / 66.2 °F

weather conditions Clouds

Monthly Posts

Blog Tags