Skip to content

Follow Position

In this guide you will learn how to render an interactive map, showing the current position of the device on the map using the navigation arrow/ position tracker, and follow the position, if the device (such as the phone on which this example is running) is in motion.


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


It is required that you complete the Environment Setup - Flutter Examples guide before starting this guide.

Run the example

Start a terminal/command prompt and go to the follow_position directory, within the flutter examples directory

Build and run the example:

Build and run

follow_position - example flutter screenshot

Note - the gem_kit directory containing the Maps SDK for Flutter should be in the plugins directory of the example, e.g. follow_position/plugins/gem_kit - see the environment setup guide above.

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:

flutter run

follow_position - example flutter screenshot

If such a question appears, select the chrome browser; in the above example, press 2.

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

In android/app/src/main/AndroidManifest.xml add the location permissions required for actual navigation, below the top <manifest xmlns:android line, as shown:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

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    }

in android/app/build.gradle within the android {} block, in the defaultConfig {} block, the android SDK version minSdkVersion 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:

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

Then build the apk:

flutter build apk --debug
flutter build apk --release
the apk file is located in the build/app/outputs/apk/debug or build/app/outputs/apk/release subdirectory, for debug or release build respectively, within the current project directory, which is follow_position in this case.
The apk file name is app-release.apk or app-debug.apk
You can copy the apk to an android device using adb, for example:
adb push app-release.apk sdcard

And then click on the apk in the file browser on the device to install and run it.

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

platform :ios, '13.0'

Also in the ios/Podfile configuration text file, add the location permissions required for actual navigation, at the end of the file, as shown:

 1post_install do |installer|
 2  installer.pods_project.targets.each do |target|
 3    flutter_additional_ios_build_settings(target)
 5    target.build_configurations.each do |config|
 6      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
 7        '$(inherited)',
 8        ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
10      ]
11    end
12  end

In the ios/Runner/Info.plist configuration text file, add the following lines inside the <dict> </dict> block:

<string>Location is needed for map localization and navigation</string>
Run pod install in the [ios folder] ./ios/
Then go back to the repository root folder and type flutter build ios to build a
Type flutter run to build and run on an attached device.
You can open the <path/to>/ios/Runner.xcworkspace project in Xcode and execute and debug from there.

How it works

In the follow_position project directory, there is a text file named pubspec.yaml which contains project configuration and dependencies. The most important lines from this file are shown here:

 1name: follow_position
 2version: 1.0.0+1
 5  sdk: '>=3.0.5 <4.0.0'
 8  flutter:
 9    sdk: flutter
10  gem_kit:
11    path: plugins/gem_kit
13  cupertino_icons: ^1.0.2
14  intl: ^0.18.1
15  permission_handler: ^10.4.2
17# The following section is specific to Flutter packages.
19  uses-material-design: true

The project must have a name and version. The dependencies list the Flutter SDK, and the gem_kit, Maps for Flutter SDK.

The source code is in follow_position/lib/main.dart

 1import 'package:flutter/cupertino.dart';
 2import 'package:flutter/foundation.dart';
 3import 'package:flutter/material.dart';
 4import 'package:gem_kit/api/gem_mapviewpreferences.dart';
 5import 'package:gem_kit/api/gem_sdksettings.dart';
 6import 'package:gem_kit/gem_kit_map_controller.dart';
 7import 'package:gem_kit/gem_kit_position.dart';
 8import 'package:gem_kit/widget/gem_kit_map.dart';
 9import 'package:permission_handler/permission_handler.dart';
11void main() {
12  runApp(const FollowPositionApp());
15class FollowPositionApp extends StatelessWidget {
16  const FollowPositionApp({super.key});
18  @override
19  Widget build(BuildContext context) {
20    return MaterialApp(
21        title: 'Follow Position',
22        debugShowCheckedModeBanner: false,
23        theme: ThemeData(
24          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
25          useMaterial3: true,
26        ),
27        home: const FollowPositionPage());
28  }
31class FollowPositionPage extends StatefulWidget {
32  const FollowPositionPage({super.key});
34  @override
35  State<FollowPositionPage> createState() => _FollowPositionPageState();

The dart material package is imported, as well as the gem_kit packages for the map controller, which enables user input such as pan and zoom, the map package which draws the map, the position package to get the GPS position from the device sensor, and the settings and map view preferences packages. The permission_handler package is required to ask the user for access to the location (position/GPS sensor).

The map is in a widget which is the root of the application.

 1class _FollowPositionPageState extends State<FollowPositionPage> {
 2  late GemMapController _mapController;
 3  late PermissionStatus _locationPermissionStatus = PermissionStatus.denied;
 5  late PositionService _positionService;
 6  late bool _hasLiveDataSource = false;
 8  final token = 'YOUR_API_KEY_TOKEN';
10  @override
11  Widget build(BuildContext context) {
12    return Scaffold(
13      appBar: AppBar(
14        backgroundColor: Colors.deepPurple[900],
15        title: const Text('Follow Position',
16            style: TextStyle(color: Colors.white)),
17        actions: [
18          IconButton(
19              onPressed: _onFollowPositionButtonPressed,
20              icon: const Icon(
21                CupertinoIcons.location,
22                color: Colors.white,
23              ))
24        ],
25      ),
26      body: GemMap(
27        onMapCreated: _onMapCreatedCallback,
28      ),
29    );
30  }
32  // The callback for when map is ready to use
33  _onMapCreatedCallback(GemMapController controller) async {
34    // Save controller for further usage
35    _mapController = controller;
37    // Create the position service
38    _positionService = await PositionService.create(controller.mapId);
40    final settings = await SdkSettings.create(controller.mapId);
42    settings.setAppAuthorization(token);
43  }
45  _onFollowPositionButtonPressed() async {
46    if (kIsWeb) {
47      // On web platform permission are handled differently than other platforms.
48      // The SDK handles the request of permission for location
49      _locationPermissionStatus = PermissionStatus.granted;
50    } else {
51      // For Android & iOS platforms, permission_handler package is used to ask for permissions
52      _locationPermissionStatus = await Permission.locationWhenInUse.request();
53    }
55    if (_locationPermissionStatus != PermissionStatus.granted) {
56      return;
57    }
59    // After the permission was granted, we can set the live data source (in most cases the GPS)
60    // The data source should be set only once, otherwise we'll get -5 error
61    if (!_hasLiveDataSource) {
62      _positionService.setLiveDataSource();
63      _hasLiveDataSource = true;
64    }
65        // After data source is set, startFollowPosition can be safely called
66    if (_locationPermissionStatus == PermissionStatus.granted) {
67      // Optionally, we can set an animation
68      final animation = GemAnimation(type: EAnimation.AnimationLinear);
70      _mapController.startFollowingPosition(animation: animation);
71    }
72    setState(() {});
73  }

The map is initialized with the map controller and the settings. A PositionService is instantiated in the _onMapCreatedCallback() once the map is ready, to get the GPS position from the device, to be used to render the green navigation arrow/position tracker, and have the camera follow it.

The _onFollowPositionButtonPressed() function calls _mapController.startFollowingPosition(animation: animation); to return to the green navigation arrow and start following it again after a user pan or zoom on the map, which also stops following the device position, to allow viewing other parts of the map.

Setting the API key

The string "YOUR_API_KEY_TOKEN" should be replaced with your actual API key token string.

follow_position - example flutter screenshot

If location permission has not yet been granted by the user,
_locationPermissionStatus = await Permission.locationWhenInUse.request();
a dialog is shown to request permission to access the GPS sensor of the device before following device position, shown by the green navigation arrow on the map can be activated.

follow_position - example flutter screenshot