Follow Position¶
Setup¶
Prerequisites¶
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¶
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:
flutter upgrade
run the following terminal commands in the project directory,
where the pubspec.yaml
file is located:
flutter clean
flutter pub get
Run the example:
flutter run
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 }
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:
1android {
2 defaultConfig {
3 applicationId "com.magiclane.gem_kit.examples.follow_position"
4 minSdk 21
5 targetSdk flutter.targetSdk
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 }
18}
Then build the apk:
flutter build apk --debug
flutter build apk --release
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.app-release.apk
or app-debug.apk
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)
4
5 target.build_configurations.each do |config|
6 config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
7 '$(inherited)',
8 ## dart: [PermissionGroup.location, PermissionGroup.locationAlways, PermissionGroup.locationWhenInUse]
9 'PERMISSION_LOCATION=1',
10 ]
11 end
12 end
13end
In the ios/Runner/Info.plist
configuration text file, add the following
lines inside the <dict> </dict>
block:
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is needed for map localization and navigation</string>
pod install
in the [ios folder] ./ios/
flutter build ios
to build a Runner.app.flutter run
to build and run on an attached device.<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
3
4environment:
5 sdk: '>=3.0.5 <4.0.0'
6
7dependencies:
8 flutter:
9 sdk: flutter
10 gem_kit:
11 path: plugins/gem_kit
12
13 cupertino_icons: ^1.0.2
14 intl: ^0.18.1
15 permission_handler: ^10.4.2
16
17# The following section is specific to Flutter packages.
18flutter:
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';
10
11void main() {
12 runApp(const FollowPositionApp());
13}
14
15class FollowPositionApp extends StatelessWidget {
16 const FollowPositionApp({super.key});
17
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 }
29}
30
31class FollowPositionPage extends StatefulWidget {
32 const FollowPositionPage({super.key});
33
34 @override
35 State<FollowPositionPage> createState() => _FollowPositionPageState();
36}
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;
4
5 late PositionService _positionService;
6 late bool _hasLiveDataSource = false;
7
8 final token = 'YOUR_API_KEY_TOKEN';
9
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 }
31
32 // The callback for when map is ready to use
33 _onMapCreatedCallback(GemMapController controller) async {
34 // Save controller for further usage
35 _mapController = controller;
36
37 // Create the position service
38 _positionService = await PositionService.create(controller.mapId);
39
40 final settings = await SdkSettings.create(controller.mapId);
41
42 settings.setAppAuthorization(token);
43 }
44
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 }
54
55 if (_locationPermissionStatus != PermissionStatus.granted) {
56 return;
57 }
58
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);
69
70 _mapController.startFollowingPosition(animation: animation);
71 }
72 setState(() {});
73 }
74}
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 |
_locationPermissionStatus = await Permission.locationWhenInUse.request();