Flutter plot live location on Google Map with Firebase

Skohan
4 min readJan 8, 2021

Hello everyone, welcome to my first ever blog and Happy New Year! In this article, we will see how to fetch location details from firebase and plot it on the Flutter app using google maps.

First of all, we need to integrate Firebase with our Flutter app. And you can find a good step by step procedure of initializing Firebase in Flutter on FlutterFire website. It has been explained lucidly. In case you don’t have Firebase app created, head over to Firebase Console to make one.

Add the following schema in your firebase Cloud Firestore database for this tutorial’s purpose:

Collection structure of Cloud Firestore

Once it’s done, we need to get Google Map API key from google cloud console to access map functionality. You can learn more about how to get the API key from google cloud console. Once you got the key, add it to the AndroidManifest.xml file inside application tag to get it working

For android

<manifest ...
<application ...
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY HERE"/>

For iOS, specify your API key in the application delegate ios/Runner/AppDelegate.m:

#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GMSServices provideAPIKey:@"YOUR KEY HERE"];
[GeneratedPluginRegistrant registerWithRegistry:self];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

Or in your swift code, specify your API key in the application delegate ios/Runner/AppDelegate.swift:

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 KEY HERE")
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}

Note that, these above code snippets for integrating Google API are taken from the documentation of the package we are going to use now, check it out here.

Finally, to complete the setup, add google_maps_flutter package in pubspec.yaml file:

cupertino_icons: ^1.0.0
firebase_core:
cloud_firestore:
google_maps_flutter:

Let's get to the coding part now. Before we start using anything, we need to initialize the Firebase using Firebase.initializeApp(). So in our main.dart file, we’ll initialize first and then will return our home view.

Let’s create the HomeView to show the Map. We need to define the zoom level and some set of markers to plot on maps.

...
import 'package:google_maps_flutter/google_maps_flutter.dart';
const double ZOOM = 1; // You can change this value to your needsclass HomeView extends StatelessWidget {static GoogleMapController _googleMapController;
Set<Marker> markers = Set();

.
.

Google Map Controller is used to update and animate to the new location, we will assign it a value when the GoogleMap widget returns the controller to use.

Now its time to fetch some data from our Cloud Firestore. We will subscribe to FirebaseFirestore.instance.collection(“Location”).snapshots() stream for fetching location data as it will reflect the changes as soon as data updates on Firestore.

class HomeView extends StatelessWidget {
.
.
@override
Widget build(BuildContext context) {
return SafeArea(
child: StreamBuilder(
stream: FirebaseFirestore.instance.collection("Location").snapshots(),
builder: (context, snapshot) {
// Here we will return Map },
),
);
}
}

Now we will check for the data in the snapshot and return the google map with the location.

...
builder: (context, snapshot){
print(snapshot);
if (snapshot.hasData) {
//Extract the location from document
GeoPoint location = snapshot.data.docs.first.get("location");
// Check if location is valid
if (location == null) {
return Text("There was no location data");
}
// Remove any existing markers
markers.clear();
final latLng = LatLng(location.latitude, location.longitude);// Add new marker with markerId.
markers
.add(Marker(markerId: MarkerId("location"), position: latLng));
// If google map is already created then update camera position with animation
_googleMapController?.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
target: latLng,
zoom: ZOOM,
),
));
return GoogleMap(
initialCameraPosition: CameraPosition(
target: LatLng(location.latitude, location.longitude)),
// Markers to be pointed
markers: markers,
onMapCreated: (controller) {
// Assign the controller value to use it later
_googleMapController = controller;
},
);
}
return Center(
child: CircularProgressIndicator(),
);
}
...

Finally, the code for HomeView looks like this.

And that's it. We have successfully fetched location data from Firebase Firestore and plotting it on Google Maps using Flutter!!

Final results are:

Thank you for reading! You can find source code of this article on GitHub repo here.

--

--