Key Concepts

In the following use case sections, we will guide you through the most common usage scenarios and reveal tips and easy-to-understand guidelines to help you get the most out of the HERE SDK for Flutter.

How to use this Guide?

You can read this guide in any order. All sections are independent from each other, making it easy to skip any section and to dive straight into the topics which you are most interested in.

  • In the example section, you can find the example apps accompanying this user guide.
  • If you are interested in building your first app showing a HERE map, take a look at the Get Started section to guide you through the first simple steps.
  • See an overview of the available use cases covered in this Developer's Guide.

Note

If you cannot find the use case you are looking for, try to open the release notes and do a keyword search: The release notes contain all features that have been introduced since HERE SDK 4.8.2.0 - and most often they contain useful tips to get started and where to look for more content in the API Reference or this Developer's Guide.

Conventions

For this guide, we preferably avoid the use of lambda notations to show the full type of information and other details, such as callback or listener name. Since Android Studio supports one-click conversion between anonymous classes and lambdas, adapting the examples to suit your personal preference should be simple.

Dispose Objects

All HERE SDK classes will be garbage collected by Flutter if the instance is no longer referenced or set to null.

When the hosting widget's lifetime has ended, you can free resources by calling SDKNativeEngine.sharedInstance?.dispose(). Also, all references to SDKNativeEngine must be set to null (if any). Calling dispose() will stop pending requests and close open files and databases that are still running. After calling dispose() any related HERE SDK feature should no longer be used - unless you initialize the HERE SDK again: If you have created engines like SearchEngine() or RoutingEngine() using the default constructor, then these instances need to be recreated as well. Basically, all engines that used the same instance of the SDKNativeEngine need to be recreated after it was disposed.

Callbacks and Listeners

  • The HERE SDK exposes callbacks for single event notification such as for search results.
  • For reoccurring event notifications such as for gesture events, listeners are used. When multiple listeners can be set, then the method pattern add_x() and remove_x() is used as naming convention. If only one listener can be set at a time, the set_x() pattern is used that can be set to null to stop listening.
  • It is the responsibility of the developer to handle errors inside the scope of a callback gracefully: As a guideline, code that can throw an exception should be handled.

Debug Logs

You can use the LogAppender interface to insert your own log class into the SDKNativeEngine. This way you can log HERE SDK messages for various predefined log levels even for release builds of your app.

When running an iOS simulator, you can obtain logs without running Xcode by executing the following command from the terminal:

xcrun simctl spawn booted log stream --level debug

Code Snippets

The shown code snippets cover best practice example code ready to be used for your own applications. However, for the sake of simplicity and to not shadow the educational approach of this guide, not all edge scenarios may be handled, especially when it comes to error handling or robust threading. In some cases, the obvious code is left out, but it can be found in the accompanying example apps that can be built and deployed instantly on any supported device with a set of valid HERE credentials.

Design Principles

The accompanying example apps follow the same structure. As much as possible the HERE SDK example code is decoupled from the surrounding platform code. We hope this makes it easier to see the relevant parts of the shown APIs. Each example app follows the same entry point from which the HERE SDK is initialized. Since each app is focusing on a different aspect of the HERE SDK, that code can be found in a single class postfixed with "...Example.dart" in its class name. Most often this class gets a reference to a MapView to start its work.

Despite the popular phrase that "everything is a widget", the example code is kept free of most Flutter dependencies - instead it's mostly pure Dart code that shows how the HERE SDK can be used.

Deprecations and Beta Versions

The team behind the HERE SDK is constantly trying to review and to improve the available APIs in order to provide the most flexible and yet the most simple-to-use APIs along with consistent interfaces.

At the same time, we want to ensure stable APIs across our releases that usually happen bi-weekly. Therefore, we follow a deprecation process: Our policy is to keep deprecated APIs for two major versions starting from the next major version after the deprecation was announced in our Release Notes, which means somewhere between six and nine months. In the API Reference you can always see which versions are affected, when an interface was marked as deprecated.

Some of our new and eventually unstable APIs are labelled as "beta" in our API Reference. Beta releases do not follow a deprecation process unless otherwise noted. If you use beta APIs, be aware that there could be a few bugs and unexpected behaviors.

Of course, we are always interested to hear your feedback for possible improvements.

Dependency Management

Currently, dependency management, for example, via https://pub.dev/, is not yet supported. This means that the HERE SDK plugin must be copied locally to an application project as described in the Get Started section.

Use The HERE SDK With Other Frameworks

You can use the HERE SDK with other frameworks. For example, it is possible to combine an open street map with a SearchEngine, if you wish to do so.

  • Xamarin: The HERE SDK does not support Xamarin, but customers can implement a wrapper for Xamarin on top of the public APIs offered by the HERE SDK. We do no commit to make changes to the HERE SDK to support the related test tooling for Xamarin.

  • React Native: React Native is not supported. However, customers can implement a wrapper on their own, but we do not provide any support for such a task.

Transactions and Usage Statistics

The HERE SDK does not offer direct APIs to query how many requests or transactions an app has made - however, you can use an external REST API for this. With the HERE Usage API you can request such data. Example for org ID org123456789 and a start and end date:

https://usage.bam.api.here.com/v2/usage/realms/org123456789?startDate=2022-07-01T10:39:51&endDate=2022-08-30T10:39:51

For more details, please refer to the cost management documentation.

Is the HERE SDK Thread Safe?

The HERE SDK is not guaranteed to be thread safe and it is required to make calls to the SDK from the main thread. Internally, the HERE SDK will offload most of its work to a background thread, but callbacks to your code will always occur on the main thread. In general, thread safety is the responsibility of the caller. For example, it is unsafe to reuse an engine on different threads unless your code is synchronized.

Use TaskHandles to Cancel Asynchronous Operations

Most asynchronous methods provide a TaskHandle as immediate return value, while the final result of the operation will be returned in a completion handler with a delay. The TaskHandle provides status information and it allows to abort an ongoing operation.

Support for Native Views

The HereMap on Android allows to use the Hybrid Composition mode. By default, the Virtual Display mode is used by the map view. In order to use the Hybrid Composition mode for native views, set the optional constructor parameter mode when creating a HereMap like this: HereMap(mode: NativeViewMode.hybridComposition, ...).

The Hybrid Composition mode is recommended for devices running Android 12 or higher. Note that it can cause performance impacts on lower Android versions. More information about Hybrid Composition and Virtual Display modes can be found here.

Unit Tests

It's easy to write unit tests for your app logic that uses the HERE SDK as all classes are fully mockable. Below you can see an example using Mockito. This will also work with most other frameworks that allow to create mocked objects:

([Angle])
void main() {
  group('Angle', () {
    test('test Angle', () {
      var mockAngle = MockAngle();

      when(mockAngle.degrees).thenReturn(10.0);

      expect(mockAngle.degrees, 10.0);
      verify(mockAngle.degrees).called(1);
    });
  });
}

Note that above we add the Mockito annotation @GenerateMocks([Angle]) to create a mock of the HERE SDK class Angle. In order to access the automatically created mock named MockAngle you need to import the created file, for example: import 'main_test.mocks.dart'.

For more information on unit testing for Flutter in general, refer to this introduction.

Check the UnitTesting example app to find more use case examples.

Coverage

Consult the coverage page to get detailed information on supported countries and languages per feature.

Defining a Scope

Optionally, you can define several scopes for an application - for example, to define a debugScope for testing your app. For a production version of your app, you may decide to leave the scope just empty, which is the default value. See the IAM Guide for more details on how to set up a project ID.

Each app belongs at least to one project. In the Projects Manager via your HERE platform account, select Projects: This allows you to see the available project IDs. You can also add more. Each project ID shows a HRN value.

Set the HRN value as scope in your plist file as follows:

<key>HERECredentials</key>
<dict>
    <key>AccessKeyId</key>
    <string>YOUR_ACCESS_KEY_ID</string>
    <key>AccessKeySecret</key>
    <string>YOUR_ACCESS_KEY_SECRET</string>
    <!-- Optionally, set a project scope. -->
    <key>Scope</key>
    <string>YOUR_PROJECT_SCOPE</string>
</dict>

For the AndroidManifest, do:

<!-- Optionally, set a project scope. -->
<meta-data
   android:name="com.here.sdk.access_scope"
   android:value="YOUR_PROJECT_SCOPE" />

Follow this guide to see how you can manage your projects.

Note that a project ID must be unique and cannot be changed for the lifetime of the organization's account. Project IDs must be between 4 and 16 characters in length. They affect also the HRN value. If the scope/HRN is set by an application, it will be used for authentication and the internal token creation of an application. If an unknown scope is set, any authentication attempt would fail and the application logs would indicate this.

Engines

The HERE SDK contains several modules - or engines as we call them - to execute specific tasks such as calculating a route with the RoutingEngine or requesting search results via the SearchEngine. There are many more engines you can use with the HERE SDK and you can read more about them in the dedicated chapters below. However, most engines share common concepts that makes it easier to use them. For example:

  • All engines execute their tasks asynchronously and receive their results on the main thread.
  • All engines share similar interfaces, callbacks and error handling.
  • It is possible to start multiple instances of an engine in parallel.
  • An online connection is required.

Below you can find an overview of the most common engines in the HERE SDK:

  • SearchEngine: Includes all functionality to search for places, suggestions and locations including geocoding and reverse geocoding.
  • OfflineSearchEngine: The offline version of search that makes request locally using already downloaded map data.
  • RoutingEngine / TransitRoutingEngine: Allows to calculate routes including various options and transport types.
  • OfflineRoutingEngine: The offline version that calculates a route using already downloaded map data.
  • LocationEngine: An advanced HERE positioning solution.
  • ConsentEngine: A supportive engine that helps to aggregate the user's consent before using, for example, the LocationEngine.
  • Navigator / VisualNavigator: Although not having 'engine' in its name, these classes act as an engine and control all functionality around turn-by-turn navigation.
  • DynamicRoutingEngine: An engine that periodically searches for shorter or faster routes based on the current traffic situation. This can be useful during guidance to notify drivers on route alternatives.
  • TrafficEngine: An engine that allows to search for traffic incidents.
  • MapDownloader / MapUpdater / RoutePrefetcher: These classes perform downloads or updates of map data and mark a vital part of any application that supports an offline mode.
  • VenueEngine: Specialized engines to support the integration of private venues into your apps.
  • SDKNativeEngine: Is required to setup credentials programmatically and allows a few other advanced settings.

Note that all HERE SDK engines, except for the SDKNativeEngine, can operate independently from each other and require HERE credentials to request data.

Note

The HERE SDK does not verify credentials at instantiation time. This only happens once a feature is used that requires authentification. In case of a failure, you will get with a dedicated error message. For example, the SearchEngine will reply with a SearchError.authentificationFailed error. Other engines provide similar error codes.

Freemium credentials will work for most features, but not for features like offline maps which are exclusive for editions such as the Navigate Edition. If the credentials are invalid, the logs contain "[ERROR]" messages with a text similar to "Failed to get the authentication token: Authentication failed, error code: 1". This indicates that the credentials are not accepted when using a service. If you want to ensure that your credentials are set up correctly, use a premium feature with a specialized engine and check if the engine replies with an error value.

Any engine can be created using a parameterless constructor. Example:

try {
  _searchEngine = SearchEngine();
} on InstantiationException {
  // Handle exception.
}

Using this default constructor requires that the HERE SDK is already initialized and that a shared instance of the SDKNativeEngine was set either directly by calling SDKNativeEngine.sharedInstance = sdkNativeEngine or implicitly by calling SDKNativeEngine.makeSharedInstance(options).

For rare use case scenarios, you can use an overloaded constructor that takes an individually created instance of the SDKNativeEngine - as shown in the below section.

Initialization

Since HERE SDK 4.12.1.0, the HERE SDK needs to be initialized manually. Follow the Get Started guide to see how this can be done.

  • If your app immediately wants to show a map view after app start, then for most use cases it's sufficient to follow the Get Started guide. However:
  • If your app needs to show a map view at a later point in time or if you want to delay initialization, then it is also possible to initialize the HERE SDK at a later point in time.
  • Note: The time of initialization of the HERE SDK does not have an impact on how transactions and monthly active users (MAU) are counted.

These are the steps to initialize the HERE SDK:

  1. Call SdkContext.init(IsolateOrigin.main). Note that this does not yet init the HERE SDK.
  2. Initialize the HERE SDK by creating SDKOptions and use them to create a new SDKNativeEngine.

Make sure to call SdkContext.init(IsolateOrigin.main) once, since it initializes the Isolate and sets up other resources that are need to initialize the HERE SDK. If you have different isolates, it must be initialized for each of those isolates threads with a different init parameter. Usually, it is enough to call init() in the main() function in your main.dart file. Note that, for example, during a hot restart all existing isolates are destroyed and the HERE SDK runs SdkContext.init(IsolateOrigin.main) again. However, in such a case you would still need to call init() again if you want to launch a new custom isolate in which the HERE SDK should run.

The creation of the SDKNativeEngine and other engines such as the SearchEngine happens synchronously in a neglectable short amount of time.

You can initialize the HERE SDK in two ways:

  • Create a shared instance of the SDKNativeEngine with SDKNativeEngine.makeSharedInstance(options).
  • Create individual instances of the SDKNativeEngine via SDKNativeEngine​(options).

By calling SDKNativeEngine.makeSharedInstance(options) you create a shared instance of the SDKNativeEngine that can be used by the HERE SDK. This singleton approach allows easy creation of engines such as the SearchEngine, because you can use the default constructor (SearchEngine()) that requires no parameters. Internally, the SearchEngine will use the shared instance of the SDKNativeEngine you have created at initialization time. Therefore, when you re-initialize the HERE SDK, also all engines that have been created using the parameterless constructor, need to be created again.

Alternatively, for rare use cases, you can set an individual SDKNativeEngine instance for each of the feature engines:

SearchEngine searchEngine = SearchEngine(sdkNativeEngine);

In general, it should not be necessary to initialize the SDKNativeEngine multiple times. Only one shared instance can be set at a time, which happens implicitly when calling SDKNativeEngine.makeSharedInstance(options). Alternatively, you can use the available constructor to create an instance of the SDKNativeEngine directly: If you create multiple instances individually, then no shared instance is set - and each feature engine needs to be created with an instance of a SDKNativeEngine as constructor parameter - like shown above. This way you can use feature engines such as the SearchEngine or the RoutingEngine with different instances of the SDKNativeEngine that can hold different SDKOptions.

Note that any individual instance can be set explicitly as shared instance by calling SDKNativeEngine.sharedInstance = sdkNativeEngine. Attention: In this case, make sure to dispose() any previous instance by calling await SDKNativeEngine.sharedInstance?.dispose(). Note that this is not necessary when creating a global instance by calling SDKNativeEngine.makeSharedInstance(options) - for convenience, this call internally disposes any previously shared instance.

Note

For most use cases it is not recommended to create multiple instances: In case of doubt, we recommend to initialize the HERE SDK only via SDKNativeEngine.makeSharedInstance(options) as shown in the Get Started guide. It is possible to use this initialization method each time the HERE SDK is needed and to dispose the SDKNativeEngine thereafter: For example, for each widget. However, for most cases it can be more efficient if the HERE SDK is initialized only once during the lifetime of an application.

Multiple SDKNativeEngine instances can’t have the same access key id and the cache path is ensured to be unique per access key id. If a 2nd instance is created with an access key id that is already in use, then an InstantiationException is thrown: As a rule of thumb, when you need multiple instances, you also need a distinct set of credentials for each.

Note

The access key id part of your credentials is tied to the cache path. When credentials are changed at runtime, it may look like that the previous cache is gone, but it still exists and it is not cleared automatically after disposing the SDKNativeEngine or after setting new credentials. Since new credentials have been set, the cache path has just been changed. For example, when the previous credentials are restored, the previous cache can be used again.

More information on the cache can be found here.

Tip: Protect Credentials

Your credentials should be protected to provide misuse by other parties that are not intended to use them.

One option to keep credentials secure is to store them on a secure server and retrieve them by requests using SSL connections.

For best practice, consider:

  • To avoid keeping sensitive data in plain text.
  • To transfer credentials using a secure communication channel.
  • To store credentials using device security mechanisms and strong encryption ciphers.
  • To add anti-tampering and anti-debugging code, so that a potential attacker cannot intercept data during dynamic runtime execution.
  • Track the application usage to detect anomalies.

Use Engines with or without a Map View

Engines do not need a map view to operate. Therefore it is possible to run an engine as a stand-alone, without any map view added to your application. This way, you can build an app solely around a specific engine. With or without a map view - the procedure to create a new engine is exactly the same. Just make sure to initialize the HERE SDK beforehand.

Android Permissions

The HERE SDK for Flutter automatically merges all required permissions to the AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Note

These permissions are not sensitive and are immediately granted upon installation by the system - they are always needed, as the HERE SDK needs to have a working internet connection. It is not a requirement to handle these permissions and there are no HERE SDK specific requirements on how to handle permissions.

However, be aware that a user can deny any permission after installation via the device's app settings. You can use a convenience class to notify the user upon app launch like shown here. Note that Flutter itself does not provide any mechanism to handle permissions - and the accompanying Flutter example apps do not utilize any specific Android permission handling. If no internet connection is available, most HERE SDK services will indicate this with an appropriate error message.

Note

For some HERE SDK features, like HERE Positioning, you need additional permissions. See the dedicated Find your Location section how to handle them.

HERE SDK Options

The HERE SDK can be initialized with various options that can be set either directly for the SDKNativeEngine or when initializing the engine with SDKOptions.

None of the options are persisted - unless otherwise notes in the API Reference: This means, whenever you initialize the HERE SDK again, the previous options have to be set again if you want to keep them.

The same applies to options you can set for the various feature engines or when using a feature such as the RoutingEngine to calculate a Route with, for example, CarOptions.

Offline Switch

The HERE SDK offers a global offline switch to make the HERE SDK radio-silent. This offline mode prevents the HERE SDK from initiating any online connection:

SDKNativeEngine.sharedInstance?.isOfflineMode = true;

This mode will, for example, prevent that new map tiles are loaded into the cache. If you are using the Navigate Edition, then you can still use features such as search, routing or guidance.

It does not matter if the device itself is put to flight mode or not: When active, the switch will block any attempt from the HERE SDK to make a request. Therefore, no online data will be consumed until the offline mode is disabled again.

However, when initializing the HERE SDK a few requests may still be made - if you want to start your application offline already before initializing the HERE SDK, then set the flag offlineMode in SDKOptions to true. If you do not plan to change this at runtime, then this flag alone is enough to operate fully offline.

Get Access Tokens For Use With External REST APIs

Each time the HERE SDK is initialized, a new access token is generated internally. In case of multiple SDKNativeEngine instances, each instance holds its own token. You can also refresh and fetch the token via Authentication.authenticate(SDKNativeEngine.sharedInstance, callback) where the callback provides the token via authenticationData.token - you can use this token to access external HERE REST APIs.

For using the HERE SDK itself, you do not need to know the token - it is only required under the hood and the HERE SDK is handling the token generation automatically.

To protect our backends against misusage, a rate limit may apply when too many tokens are generated or when too many services are accessed in a too short time frame. In such a case, an engine will respond with a requestLimitReached error or similar. If you expect very high app usage, please talk to your HERE representative upfront to adapt the limits where needed.

Getting Help When Bugs Occur

If you experience a crash or unexpected behavior, please Contact Us and provide detailed information on how to reproduce the issue.

Note that when crashes occur in the native C++ stack of the HERE SDK, then in the crash logs you will see only the addresses where the crash occurred. These addresses need to be symbolicated in order to see the stack trace where the crash occurred.

Note

Since HERE SDK 4.13.3 we include debug symbols in the heresdk.xcframework for iOS: Look for the dSYM files that are added for each device architecture.

For iOS apps that are deployed to App Store or via TestFlight you can find in Apple's Connect Portal the crash reports:

  • Instead of downloading the crash report click on Open in Xcode and you should see the symbolicated stack trace using the dSYM files.
  • This should also work with Firebase Crashlytics and related solutions.

Keep in mind, that the heresdk.xcframework is a fat binary and that its file size is optimized by Xcode at deployment time. That means the dSYM files are not available on the device of a user. Therefore, make sure to open Xcode on a machine where your app project is hosted.

When you reach out to us, be sure to always include at least the HERE SDK version, platform, edition and logs. Below you can find a bug report check-list that will help us to respond faster:

  • Type of the issue: For example, a crash or unexpected behavior.
    • In case of a crash, provide a crash log incl. stack trace.
    • In case of unexpected behavior, describe the expected versus the actual behavior.
  • Is the issue a regression and if yes, since when?
  • Description of the issue with detailed steps to reproduce it: Is the issue reproducible with one of our example apps, or can you provide code that isolates the issue?
  • What APIs are called (if applicable)? Try to list all parameters and options.
  • Reproducibility rate?
  • Provide information about the environment such as OS, IDE, device / simulator (OS, name).
  • Map data version / used catalog (if relevant).
  • List other frameworks or plugins that are used, including version information (if applicable).
  • Add screenshots or a video (if applicable).
  • In case of search or routing issues, provide the geographic coordinates where the issue occurred or a GPX trace.

Make sure to check our Release Notes where we list known issues. Please also make sure to follow the latest instructions and code examples listed in the related sections of this Developer's Guide to avoid implementation issues.

results matching ""

    No results matching ""