Find your Location

One of the main reasons to use a mapping application is to find out where you are.

The LocationEngine provided by the HERE SDK implements a comprehensive location solution that works with several location sources such as GPS or other Global Navigation Satellite System (GNSS) receivers, mobile network signals and Wi-Fi network signals to determine accurate locations.

At a glance

Integrating the HERE SDK location features requires at least the following steps:

  1. Add the required permissions to your manifest file (for Android) and your .plist file (for iOS) and request the permissions from the user.
  2. Create a ConsentEngine and show a consent dialog whether data can be collected by the LocationEngine or not.
  3. Show the outcome of the consent dialog and allow the user to revoke a previous decision.
  4. Create a LocationEngine and set at least one LocationUpdateListener.
  5. Start the LocationEngine once and set the desired accuracy level.
  6. Receive Location updates and handle them in your app.

Add the Required Permissions

Flutter itself provides no permission handling. Therefore, you need to adapt a few generated files for your Android and iOS native projects.

Let's start with Android.

Before you can start using the LocationEngine in your app on Android devices, you will need to add the required permissions to the app's AndroidManifest.xml file (located in your_project_dir/android/app/src/main/):

...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" android:maxSdkVersion="22" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

If your application targets Android SDK version 23 or higher, you can leave out the READ_PHONE_STATE permission.

If your application targets Android SDK version 28 or lower, you can leave out the ACTIVITY_RECOGNITION permission.

Next, we can move on to iOS.

Add to the app's Info.plist file (located in your_project_dir/ios/Runner/):

<key>UIRequiredDeviceCapabilities</key>
<array>
   <string>location-services</string>
   <string>gps</string>
</array>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
   <string>This app needs to access your current location to display it on the map.</string>
<key>NSLocationWhenInUseUsageDescription</key>
   <string>This app needs to access your current location to display it on the map.</string>
<key>NSMotionUsageDescription</key>
   <string>Motion detection is needed to determine more accurate locations, when no GPS signal is found or used.</string>

The permission_handler plugin can be used to request specific permissions from the user. Please refer to the plugin's official site for more information. Alternatively, you can find platform specific code for requesting permissions in the "Find your Location" section of the Developer's Guide for the HERE SDK for Android and Developer's Guide for the HERE SDK for iOS.

An app using native location services such as GPS will ask for the user's permission. Not all devices provide the same capabilities and may have certain hardware restrictions that can lead to varying results.

Prior to using the LocationEngine, it may be a good idea to check if the native location services are enabled. On most Android devices a user can decide to turn the location services on, and even increase the accuracy, by opening the device's Settings and navigating to the Security & location section. On most iOS devices, a user can navigate to Settings > Privacy > Location Services to make sure that the location services are on.

The LocationEngine contains functionality that can gather certain information about the surroundings of the mobile device in order to improve the HERE services used by the HERE SDK. An example of such information is the strength of the nearby Wi-Fi and mobile network signals.

The HERE SDK provides a ConsentEngine that handles the flow to acquire the user’s consent to collect such data. In addition, it allows to retrieve the current status and to revoke a previous decision whether to collect data or not. The application must ensure that this is accessible for the user at all times.

Note: Requirement

Showing a consent dialog is mandatory. The LocationEngine will not deliver location data to the app until the user has made a decision. Note that the LocationEngine will be fully operable regardless if the consent is declined by a user or not.

Two steps are required:

  • Show the consent dialog by calling consentEngine.requestUserConsent().
  • Your application must ensure to show the user's current decision and to revoke a previous decision: Get the current decision via consentEngine.userConsentState. Revoke a previous decision by allowing the user to call consentEngine.requestUserConsent() again. This must be possible at any time during the lifecycle of your app.

These steps are explained in greater detail below. See the HERE SDK Privacy Supplement for more information. Note that information is only collected if the user has given their consent. Gathered information does not identify the user, and HERE will only retain anonymized information.

Note: The above stated requirement only applies to Android applications, as currently there is no data collection in iOS platforms. This might change in the future.

On iOS devices, calling consentEngine.requestUserConsent() will not show a dialog, but will set the user's consent state to denied. The other ConsentEngine's methods and properties (userConsentState, grantUserConsent() and denyUserConsent()) work the same in both platforms.

The ConsentEngine requires Android's LocalBroadcastManager class. Add this dependency to your project by adding the following line inside the dependencies closure of the app level's build.gradle (located in your_project_dir/android/app/):

implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'

Before starting the LocationEngine, you need to ensure that the user's consent to collect the before mentioned information has been handled. It does not matter what the answer was (if the user accepted the collection of data or not), only that they were shown the consent dialog and that an answer was given. The LocationEngine will return LocationEngineStatus.USER_CONSENT_NOT_HANDLED status when attempting to start it without having handled the user's consent.

The code snippet below creates an instance of the ConsentEngine, checks if the user’s consent has already been requested and if not, invokes a UI dialog (pictured also below) which explains the details of information gathering to the user, and provides them with the possibility to either grant or deny permission.

ConsentEngine _consentEngine = ConsentEngine();

// ...

// Check if user consent has been handled.
if (_consentEngine.userConsentState == ConsentUserReply.notHandled) {

  // Show dialog.
  _consentEngine.requestUserConsent();
}

// The execution can continue while the dialog is being shown.

Screenshot: Consent dialog.

The dialog contains a link to a web page describing the privacy practices of HERE and supports 37 languages. When shown, the dialog will be displayed according to the device's language preferences, or in English, if they are not supported.

The user's response persists between the usage sessions of the application and can be retrieved with the userConsentState property, which returns a Consent.UserReply value:

switch (_consentEngine.userConsentState) {
  case ConsentUserReply.granted:
    //The user has previously given permission.
    break;
  case ConsentUserReply.denied:
    // The user has previously denied permission.
    break;
  case ConsentUserReply.notHandled:
    //The user has not been asked for consent.
    break;
  case ConsentUserReply.requesting:
    //The dialog is currently being shown to the user.
    break;
  default:
    throw Exception("Unknown consent state.");
}

Keep in mind that the application must provide the possibility for the user to see what response they have given earlier, by accessing the userConsentState property. In addition, the application must also make it possible for the user to change their mind on the consent at any time, by calling the requestUserConsent() method and displaying the consent dialog again.

Note: Important

Currently there is no data collection on iOS platforms. This might change in the future. In the meantime, the above stated requirement only applies to Android applications. The code snippet below shows one possible way to implement a screen that shows, on Android platforms, what response the user has given to the consent as well as allows them to change their mind, and on other platforms shows a message informing the user that there is no data collection.

// ...

// Platform class from dart:io library provides a way to check on what platform your app is running.
import 'dart:io' show Platform;

// ...

class ConsentPreferencesPage extends StatefulWidget {
  ConsentPreferencesPage({Key key, this.title}) : super(key: key);

  final String title;

  
  State<ConsentPreferencesPage> createState() {
    //Use different states according to the platform the app is running on.
    if (Platform.isAndroid) {
      return _ConsentPreferencesPageAndroid();
    }
    return _ConsentPreferencesPageOther();
  }

// ...

// This state shows what response the user has given to the consent, by accessing the consentEngine.userConsentState property. Additionally, it allows the user to change their mind on the consent by including a button "Manage Consent" that calls the requestUserConsent() method and displays the consent dialog again.
class _ConsentPreferencesPageAndroid extends State<ConsentPreferencesPage> with WidgetsBindingObserver {
  final ConsentEngine _consentEngine = ConsentEngine();

  String _getConsentAnswer() {
    switch (_consentEngine.userConsentState) {
      case ConsentUserReply.granted:
        //The user has previously given permission.
        return "You have granted consent to the data collection.";
      case ConsentUserReply.denied:
        // The user has previously denied permission.
      case ConsentUserReply.notHandled:
        //The user has not been asked for consent.
      case ConsentUserReply.requesting:
        //The dialog is currently being shown to the user.
        return "You have denied consent to the data collection.";
      default:
        throw Exception("Unknown consent state.");
    }
  }

  // ...

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        margin: const EdgeInsets.only(left: 25, right: 25),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Flexible(
                child: Text(
                    'The Location Engine contains functionality that can gather certain '
                        'information about the surroundings of the mobile device in order '
                        'to improve the HERE services used by the HERE SDK. An example '
                        'of such information is the strength of the nearby Wi-Fi and '
                        'mobile network signals.'
                ),
            ),
            SizedBox(height: 20),
            Flexible(
                child: Text(
                    _getConsentAnswer(),
                ),
            ),
            SizedBox(height: 20),
            PlatformButton(
                child: const Text("Manage Consent"),
                onPressed: () {
                  setState(() {
                    _consentEngine.requestUserConsent();
                  });
                }
            ),
          ],
        ),
      ),
    );
  }

// ...

// This state informs the user that there is currently no data collection.
class _ConsentPreferencesPageOther extends State<ConsentPreferencesPage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        margin: const EdgeInsets.only(left: 25, right: 25),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Flexible(
              child: Text('This app does not collect any data on this platform.'),
            ),
          ]
        )
      )
    );
  }
}

It is possible to customize the look and the content of the dialog. For this, ask HERE to certify the application’s own customized user consent dialog. Once the certification is received the application can use the methods grantUserConsent() and denyUserConsent() to communicate the user’s response to the HERE SDK.

Learn more about this option or initiate the certification process by contacting HERE via your HERE Sales representative or via our help page.

Create a LocationEngine

Creating a new LocationEngine is simple:

LocationEngine _locationEngine = LocationEngine();

It is not possible to initialize the LocationEngine during the Application's onCreate() lifecycle. Any other point in time is fine. For example, a good place to initialize the engine may be in an Activity's onCreate()-method.

Get the Last Known Location

Once the engine is initialized, the last known location can be obtained, as long as the engine has been started at least once before and received at least one position, otherwise null will be returned. This information will remain, so the last known location will also be available between application sessions.

Location myLastLocation = _locationEngine.lastKnownLocation;

if (myLastLocation != null) {
    // Log the last known location coordinates.
    print("Last known location: " + myLastLocation.coordinates.latitude.toString() + ", " + myLastLocation.coordinates.longitude.toString());
}

Note that the LocationEngine does not need to be started nor any listener needs to be set in order to get the last known location. It is enough that the LocationEngine was successfully started once in a previous session and that a valid location event was received at least once. The Location object contains a timestamp that indicates when that location was received.

Get Notified on Location Events

Next before starting the LocationEngine, it's a good idea to register a LocationStatusListener so that you will be notified of changes in the engine's status. To do so, implement the LocationStatusListener abstract class and register it with the location engine's addLocationStatusListener() method. Check the API Reference for more information on the different statuses.

class PositioningExample implements LocationStatusListener {

  
  onFeaturesNotAvailable(List<LocationFeature> features) {
    for (var feature in features) {
      print("Feature not available: " + feature.toString());
    }
  }

  
  onStatusChanged(LocationEngineStatus locationEngineStatus) {
    print("LocationEngineStatus: " + locationEngineStatus.toString());
  }

// ...

// Add the listener.
_locationEngine.addLocationStatusListener(this);

After a successful start, LocationStatusListener will always receive status LocationEngineStatus.engineStarted, and after a successful stop, it will always receive status LocationEngineStatus.engineStopped.

Additionally, through the listener's onFeaturesNotAvailable() callback you will be notified of any LocationFeature that is not available. If a feature that you need is not available, contact your HERE representative.

The last thing to consider before starting the engine is registering a LocationUpdateListener, which provides a callback that sends a notification once a new Location is detected. You can do so in a similar way as with the previously mentioned LocationStatusListener:

class PositioningExample implements LocationUpdateListener {
    
    onLocationUpdated(Location location) {
        print("Received location: " + location.coordinates.latitude.toString() + ", " + location.coordinates.longitude.toString());
    }

// ...

// Add the listener.
_locationEngine.addLocationUpdateListener(this);

The callback onLocationUpdated() is received on the main thread - same as for all other callbacks.

Except for the current geographic coordinates and the timestamp, all other Location fields are optional. For example, the received Location object may contain the information about the bearing angle, as well as the current speed, but this is not guaranteed to be available. Unavailable values will be returned as null. What kind of sources are used for positioning (as defined by the LocationAccuracy used to start the engine, see the Start and Stop Receiving Locations section below), and the device's capabilities affect what fields will be available.

You can add as many LocationStatusListener and LocationUpdateListener as you need by calling the respective addLocationStatusListener() and addLocationUpdateListener() methods.

Start and Stop Receiving Locations

You are now ready to call the LocationEngine's startWithLocationAccuracy() method:

class PositioningExample implements LocationUpdateListener, LocationStatusListener {

    LocationEngine _locationEngine = LocationEngine();
    ConsentEngine _consentEngine = ConsentEngine();

// ...

    if (_consentEngine.userConsentState == ConsentUserReply.notHandled) {
        _consentEngine.requestUserConsent();
    }

// ...

    startLocating();

// ...

void startLocating() {
    _locationEngine.addLocationUpdateListener(this);
    _locationEngine.addLocationStatusListener(this);
    _locationEngine.startWithLocationAccuracy(LocationAccuracy.bestAvailable);
}

The most straightforward way to start the engine is by passing it one of the pre-defined LocationAccuracy modes, as in the code snippet above. See the table below or check the API Reference for more information about all the available modes.

After the LocationEngine has been started, you will receive LocationEngineStatus.alreadyStarted if you try to start it again without calling stop() first. You can use the method isStarted() to check if the engine is started or not. Similarly, if you have started a LocationEngine and try to start another one without stopping the first, you will get LocationEngineStatus.alreadyStarted error. Only one engine can be started at a time.

If you don't want to receive more location updates, you can stop the engine by calling the stop() method. Remember to remove the listeners when they are no longer needed:

void stopLocating() {
    _locationEngine.removeLocationStatusListener(this);
    _locationEngine.removeLocationUpdateListener(this);
    _locationEngine.stop();
}

Specify Location Options on Android Devices

If you are targeting Android devices and want more control over what options are taken into account when generating the locations, you can create a LocationOptions object, configure it to your liking, and start the engine by calling the startWithLocationOptions(locationOptions) method.

// ...

// Create a new LocationOptions object. By default all options are enabled.
LocationOptions locationOptions = LocationOptions();

// Use WiFi and satellite (GNSS) positioning only.
locationOptions.wifiPositioningOptions.enabled = true;
locationOptions.satellitePositioningOptions.enabled = true;
locationOptions.sensorOptions.enabled = false;
locationOptions.cellularPositioningOptions.enabled = false;

// Receive a location approximately every minute, but not more often than every 30 seconds.
locationOptions.notificationOptions.smallestIntervalMilliseconds = 30000;
locationOptions.notificationOptions.desiredIntervalMilliseconds = 60000;

_locationEngine.startWithLocationOptions(locationOptions);

// ...

Note: On iOS plaftorms, startWithLocationOptions() will return LocationEngineStatus.notSupported.

The table below shows an overview of the available LocationAccuracy modes, and how they are internally translated to LocationOptions in Android and to CLLocationAccuracy modes in iOS:

LocationAccuracy LocationOptions (Android) CLLocationAccuracy (iOS)
BEST_AVAILABLE cellularPositioningOptions.enabled = true
satellitePositioningOptions.enabled = true
wifiPositioningOptions.enabled = true
sensorOptions.enabled = true
notificationOptions.desired_interval_millisec = 30000 (30s)
notificationOptions.smallest_interval_millisec = 1000 (1s)
kCLLocationAccuracyBest
NAVIGATION cellularPositioningOptions.enabled = false
satellitePositioningOptions.enabled = true
wifiPositioningOptions.enabled = true
sensorOptions.enabled = true
notificationOptions.desired_interval_millisec = 1000 (1s)
notificationOptions.smallest_interval_millisec = 1000 (1s)
kCLLocationAccuracyBestForNavigation
TENS_OF_METERS cellularPositioningOptions.enabled = false
satellitePositioningOptions.enabled = false
wifiPositioningOptions.enabled = true
sensorOptions.enabled = true
notificationOptions.desired_interval_millisec = 30000 (30s)
notificationOptions.smallest_interval_millisec = 1000 (1s)
kCLLocationAccuracyNearestTenMeters
HUNDREDS_OF_METERS cellularPositioningOptions.enabled = true
satellitePositioningOptions.enabled = false
wifiPositioningOptions.enabled = true
sensorOptions.enabled = false
notificationOptions.desired_interval_millisec = 30000 (30s)
notificationOptions.smallest_interval_millisec = 1000 (1s)
kCLLocationAccuracyHundredMeters
KILOMETERS cellularPositioningOptions.enabled = true
satellitePositioningOptions.enabled = false
wifiPositioningOptions.enabled = false
sensorOptions.enabled = false
notificationOptions.desired_interval_millisec = 30000 (30s)
notificationOptions.smallest_interval_millisec = 1000 (1s)
kCLLocationAccuracyThreeKilometers
Table: Mapping of LocationAccuracy to LocationOptions and CLLocationAccuracy.

The desired interval is not guaranteed by the LocationEngine, so it is possible that the locations will be delivered more or less often. The smallest interval, on the other hand, guarantees that the locations are not provided more often than the defined value.

Access Accuracy Information from a Location

In Android, the field horizontalAccuracyInMeters found in the Location object (also known as radius of uncertainty) tells us that the true geographic coordinates lie with a probability of 68% within that radius. This can be used to draw a halo indicator around the current location.

Illustration: Radius of uncertainty.

Similarly for the altitude, a verticalAccuracyInMeters value of 10 meters means that the real altitude lies with a probability of 68% in the range between altitude - 10m and altitude + 10m.

On Android devices, the coordinates.altitude value is given in relation to the WGS 84 reference ellipsoid. On iOS devices, the coordinates.altitude value is given in relation to the mean sea level instead.

Achieving probabilities other than 68% (CEP68)

What if the given probability of 68% (CEP68) is not enough - is it possible to achieve an accuracy of 99%? Yes, it is: Since the given circular error probability (CEP) follows a chi-squared distribution with two degrees-of-freedom, it is easy to calculate the desired probability based on the following formulas:

Probability Radius of Uncertainty
50% CEP50 = 0.78 x CEP68
60% CEP60 = 0.90 x CEP68
70% CEP70 = 1.03 x CEP68
80% CEP80 = 1.19 x CEP68
90% CEP90 = 1.42 x CEP68
95% CEP95 = 1.62 x CEP68
99% CEP99 = 2.01 x CEP68
Table: Formulas to calculate the desired probability.

The table above can be used to visualize various probability levels for a halo indicator on the map. For example, if the horizontal accuracy is 20 meters, you can (roughly) double the radius to achieve a probability of 99%. The accuracy value is always given as CEP68, that means:

CEP99 = 2.01 x CEP68 = 2.01 x 20m = 40.2m

Now you can draw a radius of 40.2 meters around the found location - and with a probability of 99%, the real location will lie within that circle. On the other hand, the probability for a radius of 0 meters is 0%.

Using the HERE SDK location features requires you to show the HERE SDK consent dialog in your application as described above. Users must be able to see their current consent decision and to revoke any previous consent decision - otherwise, you are not allowed to use the HERE SDK location features and you must refer to the platform location APIs instead.

Note that this requirement only applies to Android applications, as currently there is no data collection in iOS. This might change in the future.

Tutorial: Show your Current Location on a Map

A custom map circle can be composed out of two MapPolygon instances: one representing the radius of uncertainty as a halo, and the other one representing the center. Before the circle is updated with a current location value, a default Location is set, which can be the last known location - or just any place the user should see before the first location update arrives.

//Default start-up location.
GeoCoordinates _defaultGeoCoordinates = GeoCoordinates(52.520798, 13.409408);

// MapPolygon objects to represent a location circle.
MapPolygon _locationAccuracyCircle;
MapPolygon _locationCenterCircle;

// ...

GeoPolygon _createGeometry(GeoCoordinates geoCoordinates, double accuracyRadiusInMeters) {
    GeoCircle geoCircle = GeoCircle(geoCoordinates, accuracyRadiusInMeters);
    GeoPolygon geoPolygon = GeoPolygon.withGeoCircle(geoCircle);
    return geoPolygon;
}

// ...

Future<void> _addMyLocationToMap(GeoCoordinates geoCoordinates, double accuracyRadiusInMeters) async {
    //Transparent halo around the current location.
    _locationAccuracyCircle = MapPolygon(_createGeometry(geoCoordinates, accuracyRadiusInMeters), _colorAccuracy);
    //Solid circle on top of the current location.
    _locationCenterCircle = MapPolygon(_createGeometry(geoCoordinates, _centerRadiusInMeters), _colorCenter);

    //Add the circle to the map.
    _hereMapController.mapScene.addMapPolygon(_locationAccuracyCircle);
    _hereMapController.mapScene.addMapPolygon(_locationCenterCircle);
}

// ...

final Location lastKnownLocation = _locationEngine.lastKnownLocation;
if(lastKnownLocation != null) {
    final double accuracy = (lastKnownLocation.horizontalAccuracyInMeters != null) ? lastKnownLocation.horizontalAccuracyInMeters: 0;

    // Show the obtained last known location on a map.
    _addMyLocationToMap(lastKnownLocation.coordinates, accuracy);

    //Update the map viewport to be centered on the location.
    _hereMapController.camera.lookAtPointWithDistance(lastKnownLocation.coordinates, _cameraDistanceInMeters);
} else {
    // No last known location available, show a pre-defined location.
    _addMyLocationToMap(_defaultGeoCoordinates, 0);

    //Update the map viewport to be centered on the location.
    _hereMapController.camera.lookAtPointWithDistance(_defaultGeoCoordinates.coordinates, _cameraDistanceInMeters);
}

// ...


onLocationUpdated(Location location) {
    final double accuracy = (location.horizontalAccuracyInMeters != null) ? location.horizontalAccuracyInMeters: 0.0;
    _locationAccuracyCircle.updateGeometry(_createGeometry(location.coordinates, accuracy));
    _locationCenterCircle.updateGeometry(_createGeometry(location.coordinates, _centerRadiusInMeters));

    //Update the map viewport to be centered on the location.
    _hereMapController.camera.lookAtPointWithDistance(location.coordinates, _cameraDistanceInMeters);
}

Screenshot: Showing a custom map circle indicating current location.

As shown in the implementation above, you can get the GeoCoordinates from the Location object and pass it to the custom map circle that represents your current location. In this example, the goal is to track the user's current location - therefore, the map viewport's center location is updated as well. See the API Reference for more information on items such as polylines, polygons and markers you can add to the map.

results matching ""

    No results matching ""