DEV Community

Cover image for Live Location Tracking in Google Maps Flutter using Geolocator in 2023
Shivansh Agrawal
Shivansh Agrawal

Posted on

Live Location Tracking in Google Maps Flutter using Geolocator in 2023

The packages we need this feature are

google_maps_flutter | Flutter Package

A Flutter plugin for integrating Google Maps in iOS and Android applications.

favicon pub.dev

geolocator | Flutter Package

Geolocation plugin for Flutter. This plugin provides a cross-platform (iOS, Android) API for generic location (GPS etc.) functions.

favicon pub.dev

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

 android {
     defaultConfig {
         minSdkVersion 20
     }
 }
Enter fullscreen mode Exit fullscreen mode

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"/>
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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" />
Enter fullscreen mode Exit fullscreen mode
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(() {});

    });
  }
Enter fullscreen mode Exit fullscreen mode

Call this function in the intstate of your widget class.

@override
  void initState() {
    super.initState();
    getUserLocation();
    // _getCurrentLocation();
  }
Enter fullscreen mode Exit fullscreen mode

and in dispose call cancel this live tracking

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

    // TODO: implement dispose
    super.dispose();
  }
Enter fullscreen mode Exit fullscreen mode

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;
          },
        ),
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)