Live Location Tracking in Google Maps Flutter using Geolocator in 2023
Tags: flutter, googlema, tutorial, productivity
Published: 2023-09-03 05:36:00

The packages we need this feature are

{% embed https://pub.dev/packages/google_maps_flutter %}
{% embed https://pub.dev/packages/geolocator %}

For configuring Google Maps in Flutter we first need to set this property

```
 android {
     defaultConfig {
         minSdkVersion 20
     }
 }
```
and then Specify your API key in the application manifest android/app/src/main/AndroidManifest.xml:

<

```
manifest ...
  <application ...
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>
```
Get an API key at https://cloud.google.com/maps-platform/.
Now the real feature implementation start

First, initialize a variable of LatLng type like and a Googlemap controller to animate camera position as location changes

```
LatLng? location;
 GoogleMapController? mapController;
```
Then To get the User’s current live location continuously We will use the geolocator package

Add a foreground permission for location in android/app/src/main/AndroidManifest.xml:

```
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission
    android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
```
 

```
StreamSubscription? positionStream;
  void getUserLocation() async {
    LocationPermission permission;
    LocationSettings locationSettings;
    await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((Position position) async {
      location = LatLng(position.latitude, position.longitude);

      setState(() {});
    });

    permission = await Geolocator.requestPermission();
    if (defaultTargetPlatform == TargetPlatform.android) {
      locationSettings = AndroidSettings(
        accuracy: LocationAccuracy.high,
        forceLocationManager: true,
      );
    } else if (defaultTargetPlatform == TargetPlatform.iOS ||
        defaultTargetPlatform == TargetPlatform.macOS) {
      locationSettings = AppleSettings(
        accuracy: LocationAccuracy.high,
        activityType: ActivityType.fitness,
        distanceFilter: 100,
        pauseLocationUpdatesAutomatically: true,
        // Only set to true if our app will be started up in the background.
        showBackgroundLocationIndicator: false,
      );
    } else {
      locationSettings = const LocationSettings(
        accuracy: LocationAccuracy.high,
        distanceFilter: 100,
      );
    }

    positionStream =
        Geolocator.getPositionStream(locationSettings: locationSettings)
            .listen((Position? position) {
      location = LatLng(position!.latitude, position.longitude);
      mapController!.animateCamera(
        CameraUpdate.newCameraPosition(
          CameraPosition(
            target: LatLng(position.latitude, position.longitude),
            zoom: 14.0,
          ),
        ),
      );
      setState(() {});
     
    });
  }
```

Call this function in the intstate of your widget class.

```
@override
  void initState() {
    super.initState();
    getUserLocation();
    // _getCurrentLocation();
  }
```
and in dispose call cancel this live tracking

```
@override
  void dispose() {
    positionStream!.cancel();

    // TODO: implement dispose
    super.dispose();
  }
```
A marker will indicate user live location in Google Map like this

 

```
GoogleMap(
          markers: {
            Marker(
                markerId: const MarkerId('Live Location'),
                position: location ?? const LatLng(0, 0))
          },
       initialCameraPosition:  const CameraPosition(target: LatLng(0.0, 0.0)),
          // myLocationEnabled: true,
          // myLocationButtonEnabled: false,
          // mapType: MapType.normal,
          // zoomGesturesEnabled: true,
          // zoomControlsEnabled: false,
          // polylines: Set<Polyline>.of(polylines.values),
          onMapCreated: (GoogleMapController controller) {
            mapController = controller;
          },
        ),
```
For testing, I use the Lockito app from the Play Store

App should work like this in the video

https://youtube.com/shorts/RocbFph9QEg?feature=share