Skip to content

Custom Position Icon

This example presents how to create an app that displays a custom icon for the position tracker on a map using Flutter and GemKit.

custom_position_icon - 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 custom_position_icon 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

Saving Assets

Before running the app, ensure that you save the necessary files (such as the custom icon or 3D object) into the assets directory. For example:

  • Save your custom icon image (e.g., navArrow.png) in the assets folder.

Update your pubspec.yaml file to include these assets:

flutter:
  assets:
    - assets/

This ensures that the assets are correctly loaded and available when the app runs.

How It Works

The example app demonstrates the following features:

  • Display a custom icon for the position tracker on the map.

  • Handle user interaction to start following the current position.

custom_position_icon - 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. 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

Main Application Setup

 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;
 9import 'package:flutter/services.dart' show rootBundle;
10
11Future<void> main() async {
12  const projectApiToken = String.fromEnvironment('GEM_TOKEN');
13
14  await GemKit.initialize(appAuthorization: projectApiToken);
15
16  runApp(const MyApp());
17}

This imports necessary packages, initializes GemKit, and sets up the main entry point of the app.

custom_position_icon - example Flutter screenshot

UI and Map Interaction

 1class MyApp extends StatelessWidget {
 2  const MyApp({super.key});
 3
 4  @override
 5  Widget build(BuildContext context) {
 6    return const MaterialApp(
 7      title: 'Custom Position Icon',
 8      debugShowCheckedModeBanner: false,
 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('Custom Position Icon', style: TextStyle(color: Colors.white)),
39        actions: [
40          IconButton(
41            onPressed: _onFollowPositionButtonPressed,
42            icon: const Icon(
43              Icons.location_searching_sharp,
44              color: Colors.white,
45            ),
46          ),
47        ],
48      ),
49      body: GemMap(
50        onMapCreated: _onMapCreated,
51      ),
52    );
53  }

This code defines the main UI elements, including the map and an app bar with a button to follow the current position.

custom_position_icon - example Flutter screenshot

Map Creation and Custom Position Tracker Icon

 1// The callback for when map is ready to use.
 2void _onMapCreated(GemMapController controller) async {
 3  // Save controller for further usage.
 4  _mapController = controller;
 5
 6  // You can upload a custom icon for the position tracker, it can also be a 3D object as "quad.glb" file in the assets, or use a texture.
 7  //final bytes = await loadAsUint8List('assets/quad.glb');
 8  final bytes = await loadAsUint8List('assets/navArrow.png');
 9  setPositionTrackerImage(bytes, scale: 0.5);
10}

This method initializes the map controller, loads a custom icon for the position tracker from the assets, and applies it with a specified scale.

Handling Position Tracking

 1void _onFollowPositionButtonPressed() async {
 2  if (kIsWeb) {
 3    // On web platform permission are handled differently than other platforms.
 4    // The SDK handles the request of permission for location.
 5    _locationPermissionStatus = PermissionStatus.granted;
 6  } else {
 7    // For Android & iOS platforms, permission_handler package is used to ask for permissions.
 8    _locationPermissionStatus = await Permission.locationWhenInUse.request();
 9  }
10
11  if (_locationPermissionStatus == PermissionStatus.granted) {
12    // After the permission was granted, we can set the live data source (in most cases the GPS).
13    // The data source should be set only once, otherwise we'll get -5 error.
14    if (!_hasLiveDataSource) {
15      PositionService.instance.setLiveDataSource();
16      _hasLiveDataSource = true;
17    }
18
19    // Optionally, we can set an animation
20    final animation = GemAnimation(type: AnimationType.linear);
21
22    // Calling the start following position SDK method.
23    _mapController.startFollowingPosition(animation: animation);
24
25    setState(() {});
26  }
27}

This method handles user interaction to request location permissions, sets the live data source, and starts following the current position on the map.

Utility Functions

 1// Helper function to load an asset as byte array.
 2Future<Uint8List> loadAsUint8List(String filename) async {
 3  final fileData = await rootBundle.load(filename);
 4  return fileData.buffer.asUint8List();
 5}
 6
 7// Method that sets the custom icon for the position tracker.
 8void setPositionTrackerImage(Uint8List imageData, {double scale = 1.0}) {
 9  try {
10    MapSceneObject.customizeDefPositionTracker(imageData, SceneObjectFileFormat.tex);
11    final positionTracker = MapSceneObject.getDefPositionTracker();
12
13    positionTracker.scale = scale;
14  } catch (e) {
15    throw (e.toString());
16  }
17}

The setPositionTrackerImage method is crucial as it allows you to customize the position tracker icon with any image or 3D object. Ensure the image is correctly loaded from assets and properly scaled to fit your application’s design.

Flutter Examples

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