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 uses the iOS platform positioning, and works with several location sources such as GPS or other Global Navigation Satellite System (GNSS) receivers.

The capability of an iOS device to achieve GNSS precision depends on its hardware. Note that not all iOS devices have the hardware to support this feature. Sub-meter accuracy is currently not supported by iOS and would require a separate receiver.

Note

At a glance

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

  1. Add the required iOS permissions to your .plist file and request the permissions from the user.
  2. Create a LocationEngine and set at least one LocationDelegate.
  3. Start the LocationEngine once and set the desired accuracy level.
  4. Receive Location updates and handle them in your app.

Add the Required Permissions

Before you can start using the LocationEngine in your app, you will need to add the required permissions to the app's Info.plist file:

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

Note

Note that permission NSLocationAlwaysAndWhenInUseUsageDescription is needed only if your application wants to request location updates while on background. See chapter Enable Background Updates for additional information.

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 iOS devices, a user can navigate to Settings > Privacy > Location Services to make sure that the location services are on.

Note

Even recent iPad devices can lack the required UIRequiredDeviceCapabilities for gps. If present in the Info.plist file, the app will not install on such devices: If you remove this capability, the app will install, but the Location updates you will receive from the device will have a larger accuracy radius and are therefore quite imprecise - if there is no GPS sensor, the device may fall back to, for example, network positioning.

You can use the code snippet below to check the application's CLAuthorizationStatus and request the user authorization. Check the iOS documentation to find out more about Apple's CLAuthorizationStatus.

import CoreLocation

// ...

private func startLocating() {
    if locationEngine.start(locationAccuracy: .bestAvailable) == .missingPermissions {
        // App is missing location permission, let's request it.
        requestLocationAuthorization()
    }
}

// ...

public func requestLocationAuthorization() {
    // Get current location authorization status.
    let locationAuthorizationStatus = CLLocationManager.authorizationStatus()

    // Check authorization.
    switch locationAuthorizationStatus {
    case .restricted:
        // Access to location services restricted in the system settings.
        let alert = UIAlertController(title: "Location Services are restricted", message: "Please remove Location Services restriction in your device Settings", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
        return

    case .denied:
        // Location access denied for the application.
        let alert = UIAlertController(title: "Location access is denied", message: "Please allow location access for the application in your device Settings", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
        return

    case .authorizedWhenInUse, .authorizedAlways:
        // Authorization ok.
        break

    case .notDetermined:
        locationManager.requestWhenInUseAuthorization()
        break

    default:
        break
    }
}

As of now, on iOS, the HERE SDK will not collect any data. Therefore, no consent needs to be requested from the user in order to use the LocationEngine.

Create a LocationEngine

Creating a new LocationEngine is simple:

// Create instance of location engine.
do {
    try locationEngine = LocationEngine()
} catch let engineInstantiationError {
    fatalError("Failed to initialize LocationEngine. Cause: \(engineInstantiationError)")
}

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 nil will be returned. This information will remain, so the last known location will also be available between application sessions.

if let myLastLocation = locationEngine.lastKnownLocation {
    // Log the last known location coordinates.
    print("Last known location: '%f', '%f'", myLastLocation.coordinates.latitude, myLastLocation.coordinates.longitude)
}

Note

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 ensure that you will be notified of changes in the engine's status by conforming to the LocationStatusDelegate protocol and register it with the location engine's addLocationStatusDelegate() method. Check the API Reference for more information on the different statuses.

class PositioningExample: LocationStatusDelegate {

    func onStatusChanged(locationEngineStatus: LocationEngineStatus) {
        print("LocationEngineStatus: : \(locationEngineStatus)")
    }

    func onFeaturesNotAvailable(features: [LocationFeature]) {
        for feature in features {
            print("Feature not available: '%s'", String(describing: feature))
        }
    }

// ...

    locationEngine.addLocationStatusDelegate(locationStatusDelegate: self)

// ...

}

Note

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

Additionally, through the delegate'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. Note: LocationFeature enum is currently a pending feature.

The last thing to consider before starting the engine is conforming to the LocationDelegate protocol, which provides the onLocationUpdated() callback that sends a notification once a new Location is detected. You can do so in a similar way as with the previously mentioned LocationStatusDelegate:

class PositioningExample: LocationDelegate {

    func onLocationUpdated(location: Location) {
        print("Location updated: \(location.coordinates)")
    }

// ...

    locationEngine.addLocationDelegate(locationDelegate: self)

// ...

}

Note

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 nil. 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 LocationStatusDelegate and LocationDelegate as you need by calling the respective addLocationStatusDelegate() and addLocationDelegate methods.

Start and Stop Receiving Locations

You are now ready to call the LocationEngine's start() method by passing in it one of the pre-defined LocationAccuracy modes, as in the code snippet below:

class PositioningExample: LocationStatusDelegate, LocationDelegate {

// ...

    private func startLocating() {
        locationEngine.addLocationStatusDelegate(locationStatusDelegate: self)
        locationEngine.addLocationDelegate(locationDelegate: self)
        if locationEngine.start(locationAccuracy: .bestAvailable) == .missingPermissions {
            requestLocationAuthorization()
        }
    }

// ...

}

Note

The start() method already returns a LocationStatus: Even though we have set a LocationStatusDelegate in the line above, we consume the status immediately to check whether the location permission is granted for the application. If the permission is not granted, the OS will request permission from the user.

LocationEngine uses the iOS platform positioning to generate location updates. See the table below to understand how LocationAccuracy maps to iOS' own CLLocationAccuracy or check the API Reference for more information about all the available modes.

The table below shows the mapping of LocationAccuracy to CLLocationAccuracy.

LocationAccuracy CLLocationAccuracy
bestAvailable kCLLocationAccuracyBest
navigation kCLLocationAccuracyBestForNavigation
tensOfMeters kCLLocationAccuracyNearestTenMeters
hundredsOfMeters kCLLocationAccuracyHundredMeters
kilometers kCLLocationAccuracyThreeKilometers

After the LocationEngine has been started it remains in started state until you call stop() on it. 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 delegates when they are no longer needed:

class PositioningExample: LocationStatusDelegate, LocationDelegate {

// ...

    public func stopLocating() {
        locationEngine.removeLocationDelegate(locationDelegate: self)
        locationEngine.removeLocationStatusDelegate(locationStatusDelegate: self)
        locationEngine.stop()
    }

// ...

}

In general, it is recommended to stop the LocationEngine when an app gets disposed.

Pause Updates while Stationary

By default, the LocationEngine will automatically pause the location updates when location data is not expected to change. This can be used to improve battery life, for example when the device is stationary. This feature can be controlled by calling LocationEngine.setPauseLocationUpdatesAutomatically().

Enable Background Updates

In case you want to continue receiving location updates while the application is running in the background, you need to enable such capability by adding the following key to the app's Info.plist file:

<key>UIBackgroundModes</key>
    <array>
        <string>location</string>
        <string>processing</string>
    </array>

The "processing" mode is needed for iOS versions 13.0 and above. When added, also the following is needed:

<key>BGTaskSchedulerPermittedIdentifiers</key>
    <array>
        <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    </array>

Check Apple's iOS documentation for more details.

Additionally the user needs to be requested for autorization. The code snippet we shared in the above section Add the Required Permissions can also take care of that.

Once the autorization is cleared, you are all set. You can enable or disable location updates in the background with the LocationEngine.setBackgroundLocationAllowed() method. You can also set the visibility of the application's background location indicator with the method LocationEngine.setBackgroundLocationIndicatorVisible().

Finally, you can ensure that the location updates won't pause when the device is stationary by passing false to the LocationEngine.setPauseLocationUpdatesAutomatically() method.

Note

setBackgroundLocationAllowed() and setBackgroundLocationIndicatorVisible() will return LocationEngineStatus.notAllowed if the application does not have background location capabilities enabled. Otherwise, LocationEngineStatus.ok will be returned.

Note that the accompanying Positioning example app does not enable background updates, by default.

Access Accuracy Information from a Location

The horizontalAccuracyInMeters field, which is present in the Location object, also known as the "radius of uncertainty", provides an estimate of the area within which the true geographic coordinates are likely to lie with a 68% probability. This is used to draw a halo indicator around the current location. The illustration below depicts the inner green circle as the location.coordinates and the surrounding circle as the accuracy circle with a radius of horizontalAccuracyInMeters. The true geographical coordinates may lie inside (68%) or outside (32%) the accuracy circle.

Illustration: Radius of horizontal uncertainty and vertical uncertainty.

Likewise, in the case of altitude, if the verticalAccuracyInMeters value is 10 meters, this indicates that the actual altitude is expected to fall within a range of altitude - 10m to altitude + 10m with a probability of 68%. Other accuracy values, like bearingAccuracyInDegrees and speedAccuracyInMetersPerSecond will follow the same rule: a smaller uncertainty results in a better accuracy.

Note

The coordinates.altitude value is given in relation to the mean sea level (MSL).

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

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

Tutorial: Show your Current Location on a Map

A LocationIndicator is used for representing device's current location on map. Before the indicator 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. By default, the horizontal accuracy is visualized with a MapCircle that has a radius of horizontalAccuracyInMeters.

//Default start-up location.
private static let defaultGeoCoordinates = GeoCoordinates(latitude: 52.520798, longitude: 13.409408)

// LocationIndicator object to represent device's current location.
private var locationIndicator: LocationIndicator!

// ...

private func addMyLocationToMap(myLocation: Location) {
    // Setup location indicator.
    locationIndicator = LocationIndicator()
    // Enable a halo to indicate the horizontal accuracy.
    locationIndicator.isAccuracyVisualized = true
    locationIndicator.locationIndicatorStyle = .pedestrian;
    locationIndicator.updateLocation(myLocation)
    mapView.addLifecycleDelegate(locationIndicator)
    // Point camera to current location.
    let distanceInMeters = MapMeasure(kind: .distance,
                                      value: PositioningExample.defaultCameraDistance)
    mapCamera.lookAt(point: myLocation.coordinates,
                     zoom: distanceInMeters)                 
}

private func updateMyLocationOnMap(myLocation: Location) {
    // Update location indicator.
    locationIndicator.updateLocation(myLocation)
    // Point camera to current location.
    mapCamera.lookAt(point: myLocation.coordinates)
}

// ...

if let lastLocation = locationEngine.lastKnownLocation {
    addMyLocationToMap(myLocation: lastLocation)
} else {
    var defaultLocation = Location(coordinates: PositioningExample.defaultGeoCoordinates)
    defaultLocation.time = Date()
    addMyLocationToMap(myLocation: defaultLocation)
}

// ...

func onLocationUpdated(_ location: Location) {
    updateMyLocationOnMap(myLocation: location)
}

Screenshot: Location indicator showing current location on map.

As shown in the implementation above, you can pass the Location object to the location indicator by calling updateLocation(). In this example, the goal is to track the user's current location - therefore, the map viewport's center location is updated as well.

results matching ""

    No results matching ""