Navigation

The HERE SDK allows enables you to build a comprehensive turn-by-turn navigation experience. With this feature, your app can check the current device location against a calculated route and get navigational instructions just-in-time.

Navigation is supported for all available transport modes. For car and truck routes, the location of the device will be map-matched to the streets, while for pedestrian routes, locations are matched to unpaved dirt roads and other paths that would not be accessible to drivers.

Even without having a route to follow, the HERE SDK supports a specialized tracking mode, which provides information about the current street, the map-matched location and other supporting details such as speed limits. This mode is for drivers only.

Note that the HERE SDK provides no UI assets like, for example, maneuver arrows to indicate visual feedback. Instead, all information that is available along a route is given as simple data types, allowing you to choose your own assets where applicable.

A tailored navigation map view is not yet supported, however, usage of MapScheme.GREY_DAY is recommended.

Voice guidance is provided as maneuver notifications that can be fed as a String into any platform TTS (Text-To-Speech) solution.

Turn-By-Turn Navigation

The basic principle of turn-by-turn navigation is to frequently receive a location including speed and bearing values which is then matched to a street and compared to the desired route. A maneuver instruction is given to let you orientate where you are and where you have to go next.

When leaving the route, you can be notified of the deviation in meters - so you can decide whether to calculate a new route. And finally, a location simulator allows you to test route navigation during the development phase.

Note: Important

Application developers using turn-by-turn navigation are required to thoroughly test their applications in all expected usage scenarios to ensure safe and correct behavior. Application developers are responsible for warning app users of obligations including but not limited to:

  • Do not follow instructions that may lead to an unsafe or illegal situation.
  • Obey all local laws.
  • Be aware that using a mobile phone or some of its features while driving may be prohibited.
  • Always keep hands free to operate the vehicle while driving.
  • The first priority while driving should be road safety.

Use a Navigator to Listen for Guidance Events

Before you can start to navigate to a destination, you need two things:

  • A Route to follow.
  • A location source that periodically tells you where you are.

Unless you have already calculated a route, create one: Getting a Route instance is shown here. If you only want to start the app in tracking mode, you can skip this step.

Another requirement is to provide a class that conforms to the LocationProvider interface - as navigation is not possible without getting frequent updates on locations. The LocationProvider interface defines a few methods that allow the HERE SDK to retrieve Location updates. In the next section you can find a possible implementation. Alternatively, you can set an instance of LocationSimulator. Here we choose to use a LocationProviderImplementation. Don't forget to start the provider to send events on new Locations:

locationProvider = new LocationProviderImplementation(context);
locationProvider.start();

Now we can create a new Navigator instance where you can pass the locationProvider instance from above:

try {
    navigator = new Navigator(locationProvider);
} catch (InstantiationErrorException e) {
    throw new RuntimeException("Initialization of Navigator failed: " + e.error.name());
}

Make sure to set the route you want to follow (unless you plan to be in tracking mode only):

navigator.setRoute(route);

As a next step you may want to attach a few listeners to get notified on the route progress, on the current location, the next maneuver to take and on the route deviation:

// Notifies on the progress along the route including maneuver instructions.
navigator.setRouteProgressListener(new RouteProgressListener() {
    @Override
    public void onRouteProgressUpdated(@NonNull RouteProgress routeProgress) {
        List<SectionProgress> sectionProgressList = routeProgress.sectionProgress;
        // sectionProgressList is guaranteed to be non-empty.
        SectionProgress lastSectionProgress = sectionProgressList.get(sectionProgressList.size() - 1);
        Log.d(TAG, "Distance to destination in meters: " + lastSectionProgress.remainingDistanceInMeters);
        Log.d(TAG, "Traffic delay ahead in seconds: " + lastSectionProgress.trafficDelayInSeconds);

        // Contains the progress for the next maneuver ahead and the next-next maneuvers, if any.
        List<ManeuverProgress> nextManeuverList = routeProgress.maneuverProgress;

        ManeuverProgress nextManeuverProgress = nextManeuverList.get(0);
        if (nextManeuverProgress == null) {
            Log.d(TAG, "No next maneuver available.");
            return;
        }

        int nextManeuverIndex = nextManeuverProgress.maneuverIndex;
        Maneuver nextManeuver = navigator.getManeuver(nextManeuverIndex);
        if (nextManeuver == null) {
            // Should never happen as we retrieved the next maneuver progress above.
            return;
        }

        ManeuverAction action = nextManeuver.getAction();
        String nextRoadName = nextManeuver.getNextRoadName();
        String road = nextRoadName == null ? nextManeuver.getNextRoadNumber() : nextRoadName;

        if (action == ManeuverAction.ARRIVE) {
            // We are approaching the destination, so there's no next road.
            String currentRoadName = nextManeuver.getRoadName();
            road = currentRoadName == null ? nextManeuver.getRoadNumber() : currentRoadName;
        }

        if (road == null) {
            // Happens only in rare cases, when also the fallback is null.
            road = "unnamed road";
        }

        String logMessage = action.name() + " on " + road +
                " in " + nextManeuverProgress.remainingDistanceInMeters + " meters.";

        if (previousManeuverIndex != nextManeuverIndex) {
            // Show only new maneuvers and ignore changes in distance.
            Snackbar.make(mapView, "New maneuver: " + logMessage, Snackbar.LENGTH_LONG).show();
        }

        previousManeuverIndex = nextManeuverIndex;
    }
});

// Notifies on the current map-matched location and other useful information while driving or walking.
navigator.setNavigableLocationListener(new NavigableLocationListener() {
    @Override
    public void onNavigableLocationUpdated(@NonNull NavigableLocation currentNavigableLocation) {
        MapMatchedLocation mapMatchedLocation = currentNavigableLocation.mapMatchedLocation;
        if (mapMatchedLocation == null) {
            Snackbar.make(mapView,
                    "This new location could not be map-matched. Using raw location.",
                    Snackbar.LENGTH_SHORT).show();
            updateMapView(currentNavigableLocation.originalLocation.coordinates,
                    currentNavigableLocation.originalLocation.bearingInDegrees);
            return;
        }

        Log.d(TAG, "Current street: " + currentNavigableLocation.streetName);

        // Get speed limits for drivers.
        if (currentNavigableLocation.speedLimitInMetersPerSecond == null) {
            Log.d(TAG, "Warning: Speed limits unkown, data could not be retrieved.");
        } else if (currentNavigableLocation.speedLimitInMetersPerSecond == 0) {
            Log.d(TAG, "No speed limits on this road! Drive as fast as you feel safe ...");
        } else {
            Log.d(TAG, "Current speed limit (m/s): " + currentNavigableLocation.speedLimitInMetersPerSecond);
        }

        updateMapView(mapMatchedLocation.coordinates, mapMatchedLocation.bearingInDegrees);
    }
});

// Notifies on a possible deviation from the route.
navigator.setRouteDeviationListener(new RouteDeviationListener() {
    @Override
    public void onRouteDeviation(@NonNull RouteDeviation routeDeviation) {
        if (routeDeviation.lastLocationOnRoute == null) {
            Log.d(TAG, "User was never following the route.");
            return;
        }

        // Get current geographic coordinates.
        MapMatchedLocation currentMapMatchedLocation = routeDeviation.currentLocation.mapMatchedLocation;
        GeoCoordinates currentGeoCoordinates = currentMapMatchedLocation == null ?
                routeDeviation.currentLocation.originalLocation.coordinates : currentMapMatchedLocation.coordinates;

        // Get last geographic coordinates.
        MapMatchedLocation lastMapMatchedLocationOnRoute = routeDeviation.lastLocationOnRoute.mapMatchedLocation;
        GeoCoordinates lastGeoCoordinates = lastMapMatchedLocationOnRoute == null ?
                routeDeviation.lastLocationOnRoute.originalLocation.coordinates : lastMapMatchedLocationOnRoute.coordinates;

        int distanceInMeters = (int) currentGeoCoordinates.distanceTo(lastGeoCoordinates);
        Log.d(TAG, "RouteDeviation in meters is " + distanceInMeters);
    }
});

Here we set a RouteProgressListener, a NavigableLocationListener and a RouteDeviationListener.

Inside the RouteProgressListener we can access detailed information on the progress per Section of the passed Route instance. A route may be split into several sections based on the number of waypoints and transport modes. Note that remainingDistanceInMeters and trafficDelayInSeconds are accumulated per section. We check the last item of the SectionProgress list to get the overall remaining distance to the destination and the estimated traffic delay.

Inside the RouteProgressListener we also can access the next manuever that lies ahead of us. For this we use the maneuverIndex:

// Contains the progress for the next maneuver ahead and the next-next maneuvers, if any.
List<ManeuverProgress> nextManeuverList = routeProgress.maneuverProgress;

ManeuverProgress nextManeuverProgress = nextManeuverList.get(0);
if (nextManeuverProgress == null) {
    Log.d(TAG, "No next maneuver available.");
    return;
}

int nextManeuverIndex = nextManeuverProgress.maneuverIndex;
Maneuver nextManeuver = navigator.getManeuver(nextManeuverIndex);

The maneuver information taken from navigator can be used to compose a display for a driver to indicate the next action and other useful information like the distance until this action takes place. It is recommended to not use this for textual representations, unless it is meant for debug purposes like shown in the example above. Use voice guidance instead (see below).

As the location provided by the device's GPS sensor may be inaccurate, the Navigator internally calculates a map-matched location that is given to us as part of the NavigableLocation object. This location is expected to be on a navigable path like, for example, a street. But it can also be off-track, in case the user has left the road - or if the GPS signal is too poor to find a map-matched location.

It is recommended to use the map-matched location to give the user visual feedback. For example, to update the current map view based on the map-matched location. An example for this can be seen below. Only if the location could not be map-matched, for example, when the user is off-road, it may be useful to fallback to the unmatched originalLocation.

Note that the maneuver instruction text is empty during navigation. It only contains localized instructions when taken from the route instance. The ManeuverAction enum is supposed to be used to show a visual indicator. Consult the API Reference for a full list of supported actions.

Some roads do not have a road name. In such a case, you can try to retrieve the road number instead, for example, when you are on a highway.

It is not required to trigger the above events yourself. Instead the Navigator will react on the provided locations as coming from the LocationProvider implementation.

If you detect a route deviation, you can decide based on distanceInMeters if you want to calculate a new route to the destination. distanceInMeters is the straight-line distance between the expected location on the route and your actual location. If that is considered too far, you only need to set the new route to the navigator instance - and all further events will be based on the new route. Note that previous events in the queue may still be delivered for the old route: If desired, you can attach new listeners after setting the new route to prevent this.

It is possible to feed in a new locations either by implementing a platform positioning solution or by setting up a location simulator.

The basic information flow is:

LocationProvider => Location => Navigator => Events

It is the responsibility of the developer to feed in valid locations into the LocationProvider. For each provided location, the navigator will respond with appropriate events that indicate the progress along the route, including maneuvers and a possible deviation from the expected route. The resulting events depend on the accuracy and frequency of the provided location signals.

Below you can find an example on how to handle location updates:

private void updateMapView(GeoCoordinates currentGeoCoordinates,
                           Double bearingInDegrees) {
    MapCamera.OrientationUpdate orientation = new MapCamera.OrientationUpdate();
    orientation.bearing = bearingInDegrees;
    mapView.getCamera().lookAt(currentGeoCoordinates, orientation, DEFAULT_DISTANCE_IN_METERS);
    navigationArrow.setCoordinates(currentGeoCoordinates);
    trackingArrow.setCoordinates(currentGeoCoordinates);
}

Here the main task is to update the map to the new location. Additionally, we rotate the map based on the current bearing. We also update a custom map marker to indicate the user's current location in form of a navigation arrow.

Screenshot: Turn-by-turn navigation example running on a device.

Note that we call updateMapView() from within the NavigableLocationListener - as we already have showed above. Each new location event results in a new NavigableLocation that holds a map-matched location calculated out of the original GPS signal that we have fed into the LocationProvider. This map-matched location can then be consumed - like for example, as we have done above in updateMapView().

To stop any ongoing navigation, call navigator.setRoute(null), reset the above listeners to null or simply call stop() on the LocationProvider.

For the full source code, please check the corresponding navigation example app.

Receive Waypoint Events

The Navigator class provides more useful notifications. Below is an example of how to receive notifications on passed waypoints. Note that it is possible to be notified at the destination waypoint in two alternative ways: the first example below notifies when the destination is reached - and therefore navigation can be stopped. Whereas the second code snippet below shows how to get notified on all types of waypoints including the destination waypoint.

// Notifies when the destination of the route is reached.
navigator.setDestinationReachedListener(new DestinationReachedListener() {
    @Override
    public void onDestinationReached() {
        String message = "Destination reached. Stopping turn-by-turn navigation.";
        Snackbar.make(mapView, message, Snackbar.LENGTH_LONG).show();
        stopNavigation();
    }
});

// Notifies when a waypoint on the route is reached.
navigator.setMilestoneReachedListener(new MilestoneReachedListener() {
    @Override
    public void onMilestoneReached(Milestone milestone) {
        if (milestone.waypointIndex != null) {
            Log.d(TAG, "A user-defined waypoint was reached, index of waypoint: " + milestone.waypointIndex);
            Log.d(TAG,"Original coordinates: " + milestone.originalCoordinates);
        } else {
            // For example, when transport mode changes due to a ferry.
            Log.d(TAG,"A system defined waypoint was reached at " + milestone.mapMatchedCoordinates);
        }
    }
});

The onMilestoneReached() method provides a Milestone instance that contains the information about the passed waypoints along the route. Note that only stopover waypoints are included. A Milestone includes an index that refers to the waypoint list set by the user when calculating the route. If it is not available, then the Milestone refers to a waypoint that was set during the route calculation - for example, when an additional stopover was included by the routing algorithm to indicate that a ferry must be taken.

Receive Speed Warning Events

Although you can detect speed limits when you receive a new NavigableLocation (see above), there is a more convenient solution that can help you implement a speed warning feature for your app.

onSpeedWarningStatusChanged() will notify as soon as the driver exceeds the current speed limit allowed. And it will also notify as soon as the driver is driving slower again after exceeding the speed limit:

// Notifies when the current speed limit is exceeded.
navigator.setSpeedWarningListener(new SpeedWarningListener() {
    @Override
    public void onSpeedWarningStatusChanged(SpeedWarningStatus speedWarningStatus) {
        if (speedWarningStatus == SpeedWarningStatus.SPEED_LIMIT_EXCEEDED) {
            // Driver is faster than current speed limit (plus an optional offset).
            // Play a notification sound to alert the driver.
            Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone ringtone = RingtoneManager.getRingtone(context, ringtoneUri);
            ringtone.play();
        }

        if (speedWarningStatus == SpeedWarningStatus.SPEED_LIMIT_RESTORED) {
            Log.d(TAG, "Driver is again slower than current speed limit (plus an optional offset).");
        }
    }
});

Note that onSpeedWarningStatusChanged() does not notify when there is no speed limit data available. This information is only available as part of a NavigableLocation instance.

Optionally, you can define an offset that is added to the speed limit value. You will be notified only when you exceed the speed limit, including the offset. Below, we define two offsets, one for lower and one for higher speed limits. The boundary is defined by highSpeedBoundaryInMetersPerSecond:

private void setupSpeedWarnings() {
    double lowSpeedOffsetInMetersPerSecond = 2;
    double highSpeedOffsetInMetersPerSecond = 4;
    double highSpeedBoundaryInMetersPerSecond = 25;
    SpeedLimitOffset speedLimitOffset = new SpeedLimitOffset(
            lowSpeedOffsetInMetersPerSecond, highSpeedOffsetInMetersPerSecond, highSpeedBoundaryInMetersPerSecond);

    navigator.setSpeedWarningOptions(new SpeedWarningOptions(speedLimitOffset));
}

Here we set the highSpeedBoundaryInMetersPerSecond to 25 m/s: If a speed limit sign is showing a value above 25 m/s, the offset used is highSpeedOffsetInMetersPerSecond. If it is below 25 m/s, the offset used is lowSpeedOffsetInMetersPerSecond.

For example, if the speed limit on the road is 27 m/s, the offset is 4 m/s. This means we will only receive a warning notification when we are above 31 m/s = 27 m/s + 4 m/s.

You can also set negative offset values as well. This may be useful if you want to make sure you never exceed the speed limit by having a buffer before you reach the limit. Note that you will never get notifications when you drive too slow, for example, slower than a defined offset - unless a previous speed warning has been restored.

Implement a Location Provider

A location provider is mandatory to be set for a new Navigator instance. It can feed in location data from any source. Here we show an implementation that allows to switch between native location data from the device and simulated location data for test drives.

The requirement for the Navigator is that the class fulfils the LoctionProvider interface:

public class LocationProviderImplementation implements LocationProvider {

    @Nullable
    private LocationListener locationListener;

    @Override
    public void start() {
        // Start sending location events.
    }

    @Override
    public void stop() {
        // Stop sending location events.
    }

    @Nullable
    @Override
    public LocationListener getListener() {
        return locationListener;
    }

    @Override
    public void setListener(@Nullable LocationListener locationListener) {
        this.locationListener = locationListener;
    }

The setListener() method will be used by the navigator instance to hook in by setting a new locationListener instance.

As source for GPS data, we will use the PlatformPositioningProvider as shown in the Find your Location section.

To deliver events, we need to start our platformPositioningProvider and send events to the locationListener instance:

@Override
public void start() {
    platformPositioningProvider.startLocating(new PlatformPositioningProvider.PlatformLocationListener() {
        @Override
        public void onLocationUpdated(android.location.Location location) {
            handleLocationUpdate(convertLocation(location));
        }
    });
}

private void handleLocationUpdate(Location location) {
    if (locationListener != null) {
        locationListener.onLocationUpdated(location);
    }
}

Note that the HERE SDK does not yet offer a comprehensive positioning solution. Therefore, you need to convert any native location information to the required HERE SDK Location type. This type includes bearing and speed information along with the current geographic coordinates and other information that is consumed by the HERE SDK. The more accurate and complete the provided data is, the more precise the overall navigation experience will be. An example for convertLocation() can be found in the Find your Location section.

Set up a Location Simulator

During development, it may be convenient to playback the expected progress on a route for testing purposes. The LocationSimulator provides a continuous location signal that is taken from the original route coordinates. Setting up a location simulator can be done like shown below:

private LocationSimulator createLocationSimulator(Route route) {
    double speedFactor = 10;
    int notificationIntervalInMilliseconds = 100;
    LocationSimulatorOptions locationSimulatorOptions =
            new LocationSimulatorOptions(speedFactor, notificationIntervalInMilliseconds);

    LocationSimulator locationSimulator;

    try {
        locationSimulator = new LocationSimulator(route, locationSimulatorOptions);
    } catch (InstantiationErrorException e) {
        throw new RuntimeException("Initialization of LocationSimulator failed: " + e.error.name());
    }

    locationSimulator.setListener(new LocationListener() {
        @Override
        public void onLocationUpdated(Location location) {
            if (isSimulated) {
                handleLocationUpdate(location);
            }
        }

        @Override
        public void onLocationTimeout() {
            if (isSimulated) {
                locationListener.onLocationTimeout();
            }
        }
    });

    return locationSimulator;
}

Again, we call handleLocationUpdate() to forward simulated location events to the navigator instance. We also forward possible location timeout signals. By setting LocationSimulatorOptions, we can specify, how fast the current location will move. By default, the speed factor is 1.0, which is equal to the average speed a user normally drives or walks along each route segment without taking into account any traffic-related constraints. The default speed may vary based on the road geometry, road condition and other statistical data, but it is never higher than the current speed limit. Values above 1.0 will increase the speed proportionally. If the route contains not enough coordinates for the specified time interval, additional location events will be interpolated.

Make sure to stop any ongoing simulation before starting a new one:

if (locationSimulator != null) {
    locationSimulator.stop();
}

locationSimulator = createLocationSimulator(route);
locationSimulator.start();
isSimulated = true;

Below you can see the full implementation of the class. It shows how you can seamlessly switch between simulated and real locations by calling enableRoutePlayback(Route route) and enableDevicePositioning():

import android.content.Context;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;

import com.here.sdk.core.GeoCoordinates;
import com.here.sdk.core.Location;
import com.here.sdk.core.errors.InstantiationErrorException;
import com.here.sdk.navigation.LocationListener;
import com.here.sdk.navigation.LocationProvider;
import com.here.sdk.navigation.LocationSimulator;
import com.here.sdk.navigation.LocationSimulatorOptions;
import com.here.sdk.routing.Route;

import java.util.Date;

// A class that conforms the HERE SDK's LocationProvider interface.
// This class is required by Navigator to receive location updates from either the device or the LocationSimulator.
public class LocationProviderImplementation implements LocationProvider {

    private static final String TAG = LocationProviderImplementation.class.getName();

    public static final int TIMEOUT_POLL_INTERVAL_IN_MS = 500;
    public static final int TIMEOUT_INTERVAL_IN_MS = 2000;

    // Set by the Navigator instance to listen for location updates.
    @Nullable
    private LocationListener locationListener;
    @Nullable
    public Location lastKnownLocation;

    // A loop to check for timeouts between location events.
    private final Handler timeoutHandler = new Handler();
    private final PlatformPositioningProvider platformPositioningProvider;
    private LocationSimulator locationSimulator;
    private boolean isSimulated;

    public LocationProviderImplementation(Context context) {
        platformPositioningProvider = new PlatformPositioningProvider(context);
    }

    // Provides location updates based on the given route.
    public void enableRoutePlayback(Route route) {
        if (locationSimulator != null) {
            locationSimulator.stop();
        }

        locationSimulator = createLocationSimulator(route);
        locationSimulator.start();
        isSimulated = true;
    }

    // Provides location updates based on the device's GPS sensor.
    public void enableDevicePositioning() {
        if (locationSimulator != null) {
            locationSimulator.stop();
            locationSimulator = null;
        }

        isSimulated = false;
    }

    @Override
    public void start() {
        platformPositioningProvider.startLocating(new PlatformPositioningProvider.PlatformLocationListener() {
            @Override
            public void onLocationUpdated(android.location.Location location) {
                if (!isSimulated) {
                    handleLocationUpdate(convertLocation(location));
                }
            }
        });

        timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT_POLL_INTERVAL_IN_MS);
    }

    @Override
    public void stop() {
        platformPositioningProvider.stopLocating();
        timeoutHandler.removeCallbacks(timeoutRunnable);
    }

    @Nullable
    @Override
    public LocationListener getListener() {
        return locationListener;
    }

    @Override
    public void setListener(@Nullable LocationListener locationListener) {
        this.locationListener = locationListener;
    }

    private void handleLocationUpdate(Location location) {
        lastKnownLocation = location;

        if (locationListener != null) {
            // The GPS location we received from either the platform or the LocationSimulator is forwarded to the Navigator.
            locationListener.onLocationUpdated(location);
        }
    }

    private final Runnable timeoutRunnable = new Runnable(){
        public void run(){
            try {
                timeoutLoop();
                timeoutHandler.postDelayed(this, TIMEOUT_POLL_INTERVAL_IN_MS);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    };

    private void timeoutLoop() {
        if (isSimulated) {
            // LocationSimulator already includes simulated timeout events.
            return;
        }

        if (lastKnownLocation != null) {
            double millisecondsSince1970 = lastKnownLocation.timestamp.getTime();
            double timeIntervalInMs = System.currentTimeMillis() - millisecondsSince1970;
            if (locationListener != null && timeIntervalInMs > TIMEOUT_INTERVAL_IN_MS) {
                //If the last location is older than TIMEOUT_INTERVAL_IN_MS, we forward a timeout event to Navigator.
                locationListener.onLocationTimeout();
                Log.d(TAG, "GPS timeout detected: " + timeIntervalInMs);
            }
        }
    }

    // Provides fake GPS signals based on the route geometry.
    // LocationSimulator can also be set directly to the Navigator, but here we want to have the flexibility to
    // switch between real and simulated GPS data.
    private LocationSimulator createLocationSimulator(Route route) {
        double speedFactor = 10;
        int notificationIntervalInMilliseconds = 100;
        LocationSimulatorOptions locationSimulatorOptions =
                new LocationSimulatorOptions(speedFactor, notificationIntervalInMilliseconds);

        LocationSimulator locationSimulator;

        try {
            locationSimulator = new LocationSimulator(route, locationSimulatorOptions);
        } catch (InstantiationErrorException e) {
            throw new RuntimeException("Initialization of LocationSimulator failed: " + e.error.name());
        }

        locationSimulator.setListener(new LocationListener() {
            @Override
            public void onLocationUpdated(Location location) {
                if (isSimulated) {
                    handleLocationUpdate(location);
                }
            }

            @Override
            public void onLocationTimeout() {
                if (isSimulated) {
                    locationListener.onLocationTimeout();
                }
            }
        });

        return locationSimulator;
    }

    // Converts platform location to com.here.sdk.core.Location.
    private Location convertLocation(android.location.Location nativeLocation) {
        GeoCoordinates geoCoordinates = new GeoCoordinates(
                nativeLocation.getLatitude(),
                nativeLocation.getLongitude(),
                nativeLocation.getAltitude());
        Location location = new Location(geoCoordinates, new Date());
        location.bearingInDegrees = (double) nativeLocation.getBearing();
        location.speedInMetersPerSecond = (double) nativeLocation.getSpeed();
        location.horizontalAccuracyInMeters = (double) nativeLocation.getAccuracy();

        return location;
    }
}

Additionally, we added a timeoutRunnable to poll the timestamp of the lastKnownLocation. If the last location update is older than 2 seconds, we fire a timeout event. This is needed by the Navigator to evaluate, for example, if the user is driving through a tunnel or if the signal is simply lost:

double millisecondsSince1970 = lastKnownLocation.timestamp.getTime();
double timeIntervalInMs = System.currentTimeMillis() - millisecondsSince1970;
if (locationListener != null && timeIntervalInMs > TIMEOUT_INTERVAL_IN_MS) {
    locationListener.onLocationTimeout();
}

Note that the LocationSimulator class already implements the LocationProvider interface. That means that you can pass an instance of this class directly to a Navigator instance - this can be useful, if you only plan to simulate locations without a need to switch to real GPS location data.

Voice Guidance

While driving, the user's attention should stay focused on the route. You can construct visual representations from the provided maneuver data (see above), but you can also get localized textual representations that are meant to be spoken during turn-by-turn guidance. Since these maneuver notifications are provided as a String, it is possible to use them together with any TTS solution.

A few example notifications:

Voice message: After 1 kilometer turn left onto North Blaney Avenue.
Voice message: Now turn left.
Voice message: After 1 kilometer turn right onto Forest Avenue.
Voice message: Now turn right.
Voice message: After 400 meters turn right onto Park Avenue.
Voice message: Now turn right.

To get these notifications, set up a ManeuverNotificationListener:

navigator.setManeuverNotificationListener(new ManeuverNotificationListener() {
    @Override
    public void onManeuverNotification(@NonNull String voiceText) {
        voiceAssistant.speak(voiceText);
    }
});

Here we use a helper class called VoiceAssistant that wraps a Text-To-Speech engine to speak the maneuver notification. The engine uses Android's TextToSpeech class. If you are interested, you can find this class as part of the Navigation example app on GitHub.

You can set a LanguageCode to localize the notification text and a UnitSystem to decide on metric or imperial length units:

private void setupVoiceGuidance() {
    LanguageCode ttsLanguageCode = getLanguageCodeForDevice(navigator.getSupportedLanguagesForManeuverNotifications());
    navigator.setManeuverNotificationOptions(new ManeuverNotificationOptions(ttsLanguageCode, UnitSystem.METRIC));

    // Set language to our TextToSpeech engine.
    Locale locale = LanguageCodeConverter.getLocale(ttsLanguageCode);
    if (voiceAssistant.setLanguage(locale)) {
        Log.d(TAG, "TextToSpeech engine uses this language: " + locale);
    } else {
        Log.e(TAG, "TextToSpeech engine does not support this language: " + locale);
    }
}

For this example, we take the device's preferred language settings. One possible way to get these is shown below:

private LanguageCode getLanguageCodeForDevice(List<LanguageCode> supportedVoiceSkins) {

    // 1. Determine if preferred device language is supported by our TextToSpeech engine.
    Locale localeForCurrenDevice = Locale.getDefault();
    if (!voiceAssistant.isLanguageAvailable(localeForCurrenDevice)) {
        Log.e(TAG, "TextToSpeech engine does not support: " + localeForCurrenDevice + ", falling back to EN_US.");
        localeForCurrenDevice = new Locale("en", "US");
    }

    // 2. Determine supported voice skins from HERE SDK.
    LanguageCode languageCodeForCurrenDevice = LanguageCodeConverter.getLanguageCode(localeForCurrenDevice);
    if (!supportedVoiceSkins.contains(languageCodeForCurrenDevice)) {
        Log.e(TAG, "No voice skins available for " + languageCodeForCurrenDevice + ", falling back to EN_US.");
        languageCodeForCurrenDevice = LanguageCode.EN_US;
    }

    return languageCodeForCurrenDevice;
}

Note that the HERE SDK supports 37 languages. You can query the languages from the Navigator with navigator.getSupportedLanguagesForManeuverNotifications(). All languages within the HERE SDK are specified as LanguageCode enum. To convert this to a Locale instance, you can use a LanguageCodeConverter. This is an open source utility class you find as part of the Navigation example app on GitHub.

Each of the supported languages to generate maneuver notifications is stored as a voice skin inside the HERE SDK framework. Unzip the framework and look for the folder voice_assets. You can manually remove assets you are not interested in to decrease the size of the HERE SDK package.

However, in order to fed the maneuver notification into a TTS engine, you also need to ensure that your preferred language is supported by the TTS engine. Usually each device comes with some preinstalled languages, but not all languages may be present initially.

Supported Languages for Voice Guidance

Below you can find a list of all supported voice languages together with the name of the related voice skin that is stored inside the HERE SDK framework:

  • Arabic (Saudi Arabia): ar-SA_tarik_compact
  • Czech: cs-CZ_iveta_compact
  • Danish: da-DK_magnus_compact
  • German: de-DE_anna_compact
  • Greek: el-GR_nikos_compact
  • English (British): en-GB_serena_compact
  • English (United States): en-US_tom_compact
  • Spanish (Spain): es-ES_jorge_compact
  • Spanish (Mexico): es-MX_angelica_compact
  • Farsi (Iran): fa-IR_anonymous_compact
  • Finnish: fi-FI_onni_compact
  • French (Canada): fr-CA_chantal_compact
  • French: fr-FR_audrey_compact
  • Hebrew: he-IL_carmit_compact
  • Hindi: hi-IN_lekha_compact
  • Croatian: hr-HR_anonymous_compact
  • Hungarian: hu-HU_mariska_compact
  • Indonesian: (Bahasa) id-ID_damayanti_compact
  • Italian: it-IT_alice_compact
  • Japanese: ja-JP_sakura_compact
  • Korean: ko-KR_sora_compact
  • Norwegian: (Bokmål) nb-NO_henrik_compact
  • Dutch: nl-NL_claire_compact
  • Portuguese (Brazil): pt-BR_luciana_compact
  • Polish: pt-PT_joana_compact
  • Romanian: ro-RO_ioana_compact
  • Russian: ru-RU_katya_compact
  • Slovak: sk-SK_laura_compact
  • Swedish: sv-SE_alva_compact
  • Thai: th-TH_kanya_compact
  • Turkish: tr-TR_cem_compact
  • Ukrainian: uk-UA_anonymous_compact
  • Chinese (Simplified China): zh-CN_tian-tian_compact
  • Chinese (Traditional Hong Kong): zh-HK_sin-ji_compact
  • Chinese (Traditional Taiwan): zh-TW_mei-jia_compact

Tracking

While you can use the Navigator class to start and stop turn-by-turn navigation, it is also possible to switch to a tracking mode that does not require a route to follow. This mode is also often referred to as the driver's assistance mode. It is available for car and truck transport modes.

To enable tracking, you only need to call:

navigator.setRoute(null);
locationProvider.enableDevicePositioning();

Here we enable getting real GPS locations, but you could also play back locations from any route using the LocationSimulator (as shown above).

Of course, it is possible to initialize the Navigator without setting a route instance - if you are only interested in tracking mode you don't need to set the route explicitly to null. Note that in tracking mode you only get events for the NavigableLocationListener. All other listeners will simply not deliver events when a route is not set. This enables you to keep your listeners attached and to switch between free tracking and turn-by-turn-navigation on the fly.

Tracking can be useful, when drivers already know the directions to take, but would like to get additional information such as the current street name or any speed limits along the trip.

results matching ""

    No results matching ""