Skip to content

Follow Position

This example demonstrates how to create a Flutter app that follows the device’s location on a map using GemKit, with an option to request location permissions if necessary.

follow_position - example flutter screenshot

Setup

First, get an API key token, see the Getting Started guide.

Prerequisites

Make sure you completed the Environment Setup - Flutter Examples guide before starting this guide.

Build and Run

Navigate to the follow_position directory within the Flutter examples directory. This is the project folder for this example.

Note - the gem_kit directory containing the Maps SDK for Flutter should be in the plugins directory of the example, e.g. example_pathname/plugins/gem_kit - see the environment setup guide above. Replace example_pathname with the actual example path name, such as address_search

Download project dependencies:

example flutter upgrade screenshot

flutter upgrade

example flutter clean screenshot

run the following terminal commands in the project directory, where the pubspec.yaml file is located:

flutter clean

example flutter pub get screenshot

flutter pub get

Run the example:

First, verify that the ANDROID_SDK_ROOT environment variable is set to the root path of your android SDK.

In android/build.gradle add the maven {} block as shown, within the allprojects {} block, for both debug and release builds, without the line numbers, those are for reference:

1allprojects {
2    repositories {
3        google()
4        mavenCentral()
5        maven {
6           url "${rootDir}/../plugins/gem_kit/android/build"
7        }
8    }
9}

in android/app/build.gradle within the android {} block, in the defaultConfig {} block, the android SDK version minSdk must be set as shown below.

Additionally, for release builds, in android/app/build.gradle, within the android {} block, add the buildTypes {} block as shown:

Replace example_pathname with the actual example pathname, such as center_coordinates

 1android {
 2    defaultConfig {
 3        applicationId "com.magiclane.gem_kit.examples.example_pathname"
 4        minSdk 21
 5        targetSdk flutter.targetSdk
 6        versionCode flutterVersionCode.toInteger()
 7        versionName flutterVersionName
 8    }
 9    buildTypes {
10        release {
11            minifyEnabled false
12            shrinkResources false
13
14            // TODO: Add your own signing config for the release build.
15            // Signing with the debug keys for now, so `flutter run --release` works.
16            signingConfig signingConfigs.debug
17        }
18    }
19}

Then run the project:

flutter run --debug
or
flutter run --release

In the ios/Podfile configuration text file, at the top, set the minimum ios platform to 13 like this:

platform :ios, '13.0'

Then run the project:

flutter run --debug
or
flutter run --release

How It Works

follow_position - example flutter screenshot

The example app demonstrates the following features:

  • Requesting location permissions on Android and iOS, with automatic handling on web platforms.

  • Setting the live data source for the map (typically the device’s GPS).

  • Following the device’s location on the map with optional animation.

 1import 'package:gem_kit/core.dart';
 2import 'package:gem_kit/map.dart';
 3import 'package:gem_kit/sense.dart';
 4
 5import 'package:permission_handler/permission_handler.dart';
 6
 7import 'package:flutter/foundation.dart';
 8import 'package:flutter/material.dart' hide Animation;
 9
10Future<void> main() async {
11  const projectApiToken = String.fromEnvironment('GEM_TOKEN');
12
13  await GemKit.initialize(appAuthorization: projectApiToken);
14
15  runApp(const MyApp());
16}

This code initializes the GemKit SDK with the necessary authorization and sets up the main entry point of the app.

UI and Map Integration

 1class MyApp extends StatelessWidget {
 2  const MyApp({super.key});
 3
 4  @override
 5  Widget build(BuildContext context) {
 6    return const MaterialApp(
 7      debugShowCheckedModeBanner: false,
 8      title: 'Follow Position',
 9      home: MyHomePage(),
10    );
11  }
12}
13
14class MyHomePage extends StatefulWidget {
15  const MyHomePage({super.key});
16
17  @override
18  State<MyHomePage> createState() => _MyHomePageState();
19}
20
21class _MyHomePageState extends State<MyHomePage> {
22  late GemMapController _mapController;
23
24  PermissionStatus _locationPermissionStatus = PermissionStatus.denied;
25  bool _hasLiveDataSource = false;
26
27  @override
28  void dispose() {
29    GemKit.release();
30    super.dispose();
31  }
32
33  @override
34  Widget build(BuildContext context) {
35    return Scaffold(
36      appBar: AppBar(
37        backgroundColor: Colors.deepPurple[900],
38        title: const Text('Follow Position', style: TextStyle(color: Colors.white)),
39        actions: [
40          IconButton(
41            onPressed: _onFollowPositionButtonPressed,
42            icon: const Icon(Icons.location_searching_sharp, color: Colors.white),
43          ),
44        ],
45      ),
46      body: GemMap(
47        onMapCreated: _onMapCreated,
48      ),
49    );
50  }

This code sets up the app’s user interface, including a map and a button to follow the device’s position.

Handling Location Permissions and Following Position

 1// The callback for when the map is ready to use.
 2void _onMapCreated(GemMapController controller) async {
 3  // Save controller for further usage.
 4  _mapController = controller;
 5}
 6
 7void _onFollowPositionButtonPressed() async {
 8  if (kIsWeb) {
 9    // On web platforms, permissions are handled differently.
10    _locationPermissionStatus = PermissionStatus.granted;
11  } else {
12    // Request location permission on Android and iOS platforms.
13    _locationPermissionStatus = await Permission.locationWhenInUse.request();
14  }
15
16  if (_locationPermissionStatus == PermissionStatus.granted) {
17    // Set the live data source (GPS) if not already set.
18    if (!_hasLiveDataSource) {
19      PositionService.instance.setLiveDataSource();
20      _hasLiveDataSource = true;
21    }
22
23    // Optionally, set an animation.
24    final animation = GemAnimation(type: AnimationType.linear);
25
26    // Start following the device's position.
27    _mapController.startFollowingPosition(animation: animation);
28
29    setState(() {});
30  }
31}

This code handles the process of requesting location permissions, setting the GPS as the live data source, and starting the map’s follow position mode.

Displaying Position Information

When the “Follow Position” button is pressed, the _onFollowPositionButtonPressed() callback is triggered. It requests location permission if it hasn’t been granted already, and sets the location data source to the device’s GPS sensor.
Once the permission is granted and the data source is set, the map will follow the device’s location, centering the camera on the current position. The follow position feature is disabled if the user interacts with the map, such as by panning, until the button is pressed again.

Flutter Examples

Maps SDK for Flutter Examples can be downloaded or cloned with Git