### Perform Search with GeoBias (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/quickstart
This example shows how to make a search request using the OnlineSearch API with specific search options, including a query, geobias, and a limit for results. It also includes a callback to handle successful results or failures.
```kotlin
val options = SearchOptions(
query = "TomTom",
geoBias = GeoPoint(latitude = 52.377956, longitude = 4.897070),
limit = 5
)
search.search(
options,
object : SearchCallback {
override fun onSuccess(result: SearchResponse) {
// handle success
}
override fun onFailure(failure: SearchFailure) {
// handle failure
}
}
)
```
--------------------------------
### Lane Guidance Documentation Example (Kotlin)
Source: https://developer.tomtom.com/maps/android/releases/latest
This example illustrates the usage of Simple Lane Guidance as described in the updated documentation. It clarifies usage conditions and provides a practical code snippet for better understanding.
```Kotlin
import com.tomtom.sdk.navigation.guidance.LaneGuidance
// Assuming 'laneGuidance' is an instance of LaneGuidance
// Example of checking lane guidance availability and usage:
if (laneGuidance.isAvailable()) {
// Use lane guidance information
val lanes = laneGuidance.getLanes()
for (lane in lanes) {
println("Lane: ${lane.instruction}, Type: ${lane.type}")
}
} else {
println("Lane guidance is not available.")
}
```
--------------------------------
### Plan a Route with TomTom SDK for Android
Source: https://developer.tomtom.com/maps/android/guides/routing/quickstart
This example shows how to plan a route between two GeoPoints using the TomTom Maps SDK for Android. It includes setting up route planning options and implementing a RoutePlanningCallback to handle the asynchronous response, including success, failure, and individual route planning events.
```kotlin
val amsterdam = GeoPoint(52.377956, 4.897070)
val rotterdam = GeoPoint(51.926517, 4.462456)
val routePlanningOptions = RoutePlanningOptions(itinerary = Itinerary(amsterdam, rotterdam))
routePlanner.planRoute(
routePlanningOptions,
object : RoutePlanningCallback {
override fun onSuccess(result: RoutePlanningResponse) {
// YOUR CODE GOES HERE
}
override fun onFailure(failure: RoutingFailure) {
// YOUR CODE GOES HERE
}
override fun onRoutePlanned(route: Route) {
// YOUR CODE GOES HERE
}
},
)
```
--------------------------------
### Add Map-Matched Location Provider Dependency
Source: https://developer.tomtom.com/maps/android/guides/location/quickstart
This snippet demonstrates adding the dependency for the MapMatchedLocationProvider, which provides map-matched locations generated by navigation.
```kotlin
implementation("com.tomtom.sdk.location:provider-map-matched:1.25.11")
```
--------------------------------
### Initialize MapFragment in Android
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This code demonstrates how to create and initialize a MapFragment in an Android application using Kotlin. It involves creating MapOptions with an API key and then instantiating the MapFragment.
```kotlin
val mapOptions = MapOptions(mapKey = "YOUR_TOMTOM_API_KEY")
val mapFragment = MapFragment.newInstance(mapOptions)
```
--------------------------------
### Access TomTomMap Asynchronously
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This code shows how to get the TomTomMap object asynchronously by implementing the MapReadyCallback and using the getMapAsync method. The callback is invoked when the map is ready for use.
```Kotlin
mapFragment.getMapAsync { tomtomMap: TomTomMap -> // Your code goes here }
```
--------------------------------
### Add Simulation Location Provider Dependency
Source: https://developer.tomtom.com/maps/android/guides/location/quickstart
This snippet illustrates how to add the dependency for the SimulationLocationProvider, used for simulating location updates with a provided list of locations.
```kotlin
implementation("com.tomtom.sdk.location:provider-simulation:1.25.11")
```
--------------------------------
### Initialize OnlineSearch API (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/quickstart
This code demonstrates how to initialize the OnlineSearch API instance using your TomTom API key. This instance is then used to perform various search operations.
```kotlin
val searchApi = OnlineSearch.create(context, "YOUR_TOMTOM_API_KEY")
```
--------------------------------
### Add Location Provider API Dependency
Source: https://developer.tomtom.com/maps/android/guides/location/quickstart
This snippet shows the dependency for the LocationProvider interface, which is included in all other provider dependencies and can be implemented for custom location providers.
```kotlin
implementation("com.tomtom.sdk.location:provider-api:1.25.11")
```
--------------------------------
### Initialize MapFragment in Kotlin
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This Kotlin code demonstrates how to find and cast the MapFragment from the FragmentManager in an Activity's onCreate() or a Fragment's onCreateView() method.
```Kotlin
val mapFragment = supportFragmentManager.findFragmentById(R.id.map_fragment) as? MapFragment
```
--------------------------------
### Initialize OnlineRoutePlanner in Android
Source: https://developer.tomtom.com/maps/android/guides/routing/quickstart
This code demonstrates how to initialize the OnlineRoutePlanner, the entry point for making routing requests in the TomTom Maps SDK for Android. You need to provide your TomTom API key during initialization.
```kotlin
val routePlanner = OnlineRoutePlanner.create(applicationContext, "YOUR_TOMTOM_API_KEY")
```
--------------------------------
### Enable Location Updates (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/location/built-in-location-provider
Explains how to enable the LocationProvider to start receiving location updates. This is a crucial step after setting the provider.
```Kotlin
locationProvider.enable()
```
--------------------------------
### Add Default Location Provider Dependency
Source: https://developer.tomtom.com/maps/android/guides/location/quickstart
This snippet shows how to add the dependency for the default LocationProvider, which relies on Android system location services and does not require Google services.
```kotlin
implementation("com.tomtom.sdk.location:provider-default:1.25.11")
```
--------------------------------
### Access API Key in Application Code
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
Demonstrates how to access the TomTom API key, which has been mapped to the BuildConfig class. This allows your application to use the API key for authenticating with TomTom services.
```Kotlin
val apiKey = BuildConfig.TOMTOM_API_KEY
```
--------------------------------
### Add MapFragment in XML
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This snippet shows how to declare a MapFragment in an Android XML layout file. It includes the necessary TomTom namespace and API key configuration.
```XML
```
--------------------------------
### Add Routing Dependencies for Android
Source: https://developer.tomtom.com/maps/android/guides/routing/quickstart
This snippet shows how to add the necessary TomTom SDK routing dependencies to your Android application's build.gradle.kts file. Ensure you synchronize your project after adding these lines.
```kotlin
implementation("com.tomtom.sdk.routing:route-planner-online:1.25.11")
```
--------------------------------
### Android Layout for Map Container
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This XML snippet defines a FragmentContainerView in an Android layout file. This view acts as a placeholder where the MapFragment will be dynamically added to display the map.
```xml
```
--------------------------------
### Configure Maven Repository
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
Adds the TomTom Maven repository to your project's settings.gradle.kts file. This allows Gradle to download TomTom SDK artifacts. It configures the repository to fail on project repositories, ensuring only specified repositories are used.
```Kotlin
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
maven {
url = uri("https://repositories.tomtom.com/artifactory/maven")
}
}
}
```
--------------------------------
### Declare API Key in build.gradle.kts
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
Declares the TomTom API key as a project property within the build.gradle.kts file. This makes the API key accessible for use in Gradle build configurations.
```Kotlin
val tomtomApiKey: String by project
```
--------------------------------
### Add Search Module Dependency (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/quickstart
This snippet shows how to add the TomTom Maps SDK for Android's online search module dependency to your application's build.gradle.kts file. Ensure you synchronize your project after adding the dependency.
```kotlin
implementation("com.tomtom.sdk.search:search-online:1.25.11")
```
--------------------------------
### Add Maps SDK Dependency
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
Includes the TomTom Maps SDK 'map-display' library in your application module's build.gradle.kts file. This makes the Maps SDK functionalities available for use in your Android application. A specific version is defined for the dependency.
```Kotlin
val version = "1.25.11"
implementation("com.tomtom.sdk.maps:map-display:$version")
```
--------------------------------
### Map API Key to BuildConfig
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
Configures the Android build process to generate a BuildConfig field for the TomTom API key. This allows the API key to be accessed directly from the BuildConfig class in your application code.
```Kotlin
android {
buildFeatures {
buildConfig = true
}
buildTypes.configureEach {
buildConfigField("String", "TOMTOM_API_KEY", "\"$tomtomApiKey\"")
}
}
```
--------------------------------
### Request Parking Prices (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/dynamic-data
Provides a code example for requesting parking price information using the `ParkingDetailProvider`. It demonstrates initializing the provider and making the request with `ParkingPriceOptions`, including callbacks for success and failure.
```Kotlin
parkingDetailProvider = OnlineDynamicDataProviderFactory.createParkingDetailProvider(
context,
"YOUR_TOMTOM_API_KEY",
)
parkingPriceOptions?.let { options ->
parkingDetailProvider.requestParkingPrice(
options,
object : ParkingPriceCallback {
override fun onSuccess(result: ParkingPriceResponse) {
// YOUR CODE GOES HERE
}
override fun onFailure(failure: SearchFailure) {
// YOUR CODE GOES HERE
}
},
)
}
```
--------------------------------
### Add Map Display Dependency for Android
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This snippet shows how to add the TomTom Maps SDK Map Display module dependency to your Android application's build.gradle.kts file. Ensure you have the correct version number.
```kotlin
implementation("com.tomtom.sdk.maps:map-display:1.25.11")
```
--------------------------------
### Kotlin: WaypointInstruction copy() Method
Source: https://developer.tomtom.com/maps/android/releases/latest
Provides an example of using the copy() method for the WaypointInstruction class. This method is useful for generating a new WaypointInstruction instance based on an existing one, potentially with updated properties.
```Kotlin
val originalWaypoint = WaypointInstruction(...)
val copiedWaypoint = originalWaypoint.copy()
```
--------------------------------
### Configure build.gradle.kts for TomTom Maps SDK Android
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
This snippet shows how to configure your `build.gradle.kts` file to set the minimum SDK to API level 26 and limit ABIs to arm64-v8a and x86_64, as required by the TomTom Maps SDK for Android. This ensures compatibility and prevents potential startup errors.
```kotlin
android {
defaultConfig {
minSdk = 26
ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
}
}
}
```
--------------------------------
### Enable TomTom Orbis Map Feature (Kotlin)
Source: https://developer.tomtom.com/maps/android/getting-started/migrate-to-tomtom-orbis-maps
This code demonstrates how to initialize and enable the TomTom Orbis Map feature within your Android application using the FeatureToggleController. This is a crucial step after adding the dependency.
```kotlin
FeatureToggleController.initialize(context = this)
FeatureToggleController.enable(TomTomOrbisMapFeature)
```
--------------------------------
### Get Parking Availability Options (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/dynamic-data
Demonstrates how to create `ParkingAvailabilityOptions` using the `parkingDetailId` obtained from a Fuzzy Search result. This is a prerequisite for requesting parking availability.
```Kotlin
val parkingAvailabilityOptions = searchResult.searchResultId.parkingDetailId?.let { parkingDetailId -> ParkingAvailabilityOptions(parkingDetailId) }
```
--------------------------------
### Store TomTom API Key
Source: https://developer.tomtom.com/maps/android/getting-started/project-setup
Stores your TomTom API key in the project's gradle.properties file. This is a common practice for managing sensitive information like API keys, keeping them separate from the main codebase.
```Properties
tomtomApiKey=api_key_placeholder
```
--------------------------------
### Get Parking Price Options (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/dynamic-data
Illustrates how to construct `ParkingPriceOptions`, which requires a `parkingDetailId`, and optionally accepts `startTime` and `duration` for the parking period. This is used for fetching parking price information.
```Kotlin
val parkingPriceOptions = searchResult.searchResultId.parkingDetailId?.let { parkingDetailId ->
ParkingPriceOptions(
parkingDetailId = parkingDetailId,
startTime = Calendar.getInstance(),
duration = 3.hours,
)
}
```
--------------------------------
### Add TomTom Orbis Maps Dependency (Kotlin)
Source: https://developer.tomtom.com/maps/android/getting-started/migrate-to-tomtom-orbis-maps
This snippet shows how to add the TomTom Orbis Maps SDK dependency to your Android application's build.gradle.kts file. Ensure you are using the correct version.
```kotlin
val version = "1.25.11"
implementation("com.tomtom.sdk:feature-toggle:$version")
```
--------------------------------
### Replace Fragment Container with MapFragment in Android
Source: https://developer.tomtom.com/maps/android/guides/map-display/quickstart
This Kotlin code snippet shows how to replace a FragmentContainerView in your Android layout with the initialized MapFragment using the FragmentManager. This is a standard way to embed fragments in an activity.
```kotlin
supportFragmentManager.beginTransaction()
.replace(R.id.map_container, mapFragment)
.commit()
```
--------------------------------
### Create InterpolationStrategy for Location Simulation (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/location/simulation-location-provider
Provides an example of creating an `InterpolationStrategy` for `SimulationLocationProvider`. This strategy is useful when successive locations are far apart, such as simulating movement along a route, and allows configuration of delays and speed.
```kotlin
val interpolationStrategy = InterpolationStrategy(
locations = locations,
startDelay = 1.seconds,
broadcastDelay = 500.milliseconds,
currentSpeed = metersPerSecond(13.0),
)
```
--------------------------------
### Initialize TomTom Map in XML
Source: https://developer.tomtom.com/maps/android/guides/map-display/map-configuration
Configures a `MapFragment` in an Android XML layout file. It sets essential map properties like API key, padding, camera position, zoom level, tilt, rotation, and custom styles. This approach allows for declarative map setup directly within the layout.
```XML
```
--------------------------------
### Get Asset Style URI (Android)
Source: https://developer.tomtom.com/maps/android/guides/map-display/map-styles
Provides an example of how to obtain a URI for a style file located in the application's asset directory using the Uris.forAssetFile method. This is essential for loading custom map styles packaged with the app.
```Kotlin
val styleUri = Uris.forAssetFile(assetFile = "custom_style.json")
```
--------------------------------
### Android SDK - Experimental Map API Updates
Source: https://developer.tomtom.com/maps/android/releases/release-notes
Introduces several experimental APIs for map functionality, including getting the visible region and related callbacks and failure types. Also adds a non-blocking get renderedFeatures API.
```Java
com.tomtom.sdk.map.display.annotation.ExperimentalMapGetVisibleRegionApi is now available as Experimental API.
```
```Java
com.tomtom.sdk.map.display.map.MapController.getVisibleRegion(callback: VisibleRegionCallback) is now available as Experimental API.
```
```Java
com.tomtom.sdk.map.display.map.VisibleRegionCallback is now available as Experimental API.
```
```Java
com.tomtom.sdk.map.display.map.VisibleRegionFailure(String) is now available as Experimental API.
```
```Java
com.tomtom.sdk.map.display.map.VisibleRegionFailure is now available as Experimental API.
```
```Java
Create non-blocking get renderedFeatures API.
```
--------------------------------
### Get Current Camera Tracking Mode (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/map-display/camera-and-animations
Retrieves the current camera tracking mode set for the TomTomMap instance.
```Kotlin
val cameraTrackingMode = tomTomMap.cameraTrackingMode
```
--------------------------------
### Get Current Camera Tracking Mode
Source: https://developer.tomtom.com/maps/android/guides/map-display/routes
Retrieves the currently set camera tracking mode from the TomTomMap instance. This allows checking the active tracking behavior.
```Kotlin
val cameraTrackingMode = tomTomMap.cameraTrackingMode
```
--------------------------------
### Get Last Known Location (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/location/built-in-location-provider
Shows how to access the last known GeoLocation from the LocationProvider. Returns null if a location has not yet been determined.
```Kotlin
val lastLocation = locationProvider.lastKnownLocation
```
--------------------------------
### Get POI Identifier for Details Request
Source: https://developer.tomtom.com/maps/android/guides/search/point-of-interest-details
This snippet demonstrates how to extract the searchResultId from a search response to obtain the necessary ID and source for a POI details request.
```Kotlin
val searchResultId = searchResponse.results.firstOrNull()?.searchResultId ?: return
val poiId = PoiId(searchResultId.id, searchResultId.source)
```
--------------------------------
### Initialize TomTom Map with MapOptions in Kotlin
Source: https://developer.tomtom.com/maps/android/guides/map-display/map-configuration
Demonstrates how to initialize the TomTom map in an Android application using Kotlin and the `MapOptions` object. This allows for pre-setting map configurations such as the API key, camera position, padding, and styling.
```Kotlin
val mapOptions = MapOptions(
mapKey = "YOUR_MAP_KEY",
cameraOptions = CameraOptions(position = GeoPoint(52.370216, 4.895168), zoom = 12.0),
padding = Padding(16, 16, 16, 16),
mapStyle = StyleDescriptor.Builder("path/to/custom/style.json").build(),
styleMode = StyleMode.DARK,
onlineCachePolicy = OnlineCachePolicy.NO_CACHE
)
val tomtomMap = TomTomMap(context, mapOptions)
```
--------------------------------
### Add MapPanningListener in Kotlin
Source: https://developer.tomtom.com/maps/android/guides/map-display/events-and-gestures
Adds a listener to track map panning actions. It includes methods for when panning starts, continues, and ends, allowing custom logic for each phase.
```Kotlin
tomtomMap.addMapPanningListener( object : MapPanningListener { override fun onMapPanningEnded() { // YOUR CODE GOES HERE } override fun onMapPanningOngoing() { // YOUR CODE GOES HERE } override fun onMapPanningStarted() { // YOUR CODE GOES HERE } }, )
```
```Kotlin
tomtomMap.addMapPanningListener(
object: MapPanningListener {
overridefunonMapPanningEnded(){
// YOUR CODE GOES HERE
}
overridefunonMapPanningOngoing(){
// YOUR CODE GOES HERE
}
overridefunonMapPanningStarted(){
// YOUR CODE GOES HERE
}
},
)
```
--------------------------------
### Listen to Current Location Button Clicks
Source: https://developer.tomtom.com/maps/android/guides/map-display/ui-controls
Provides an example of how to add a click listener to the current location button to handle user interactions. This is crucial for responding to button presses.
```Kotlin
Copyval uiComponentClickListener = UiComponentClickListener { /* YOUR CODE GOES HERE */ } mapFragment.currentLocationButton.addCurrentLocationButtonClickListener( uiComponentClickListener, )
```
```Kotlin
1val uiComponentClickListener = UiComponentClickListener {/* YOUR CODE GOES HERE */}
```
```Kotlin
2mapFragment.currentLocationButton.addCurrentLocationButtonClickListener(
```
```Kotlin
3 uiComponentClickListener,
```
```Kotlin
4)
```
--------------------------------
### Style Compass Button in XML
Source: https://developer.tomtom.com/maps/android/guides/map-display/ui-controls
Provides an example of how to style the CompassButton in XML. You can set attributes like background tint and visibility policy by defining a style that inherits from `BaseCompassButton`.
```XML
```
--------------------------------
### Get Fuel Price Identifier
Source: https://developer.tomtom.com/maps/android/guides/search/dynamic-data
This Kotlin code demonstrates how to extract the fuel price identifier (`fuelPriceId`) from a `SearchResult` object. This ID is necessary for requesting fuel price information.
```kotlin
val fuelPriceOptions = searchResult.searchResultId.fuelPriceId?.let { fuelPriceId -> FuelPriceOptions(fuelPriceId) }
```
--------------------------------
### Add equals, hashCode, toString to EntryPoint (Android)
Source: https://developer.tomtom.com/maps/android/releases/versions/0
Adds `equals()`, `hashCode()`, and `toString()` methods to the `com.tomtom.sdk.location.EntryPoint` class for better object comparison and representation. This is a general update for the location module.
```Java
com.tomtom.sdk.location.EntryPoint
```
--------------------------------
### Initialize Map with Style (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/map-display/map-styles
Demonstrates how to initialize a TomTom map with a specific style using `MapOptions`. This includes setting the API key and the map style descriptor.
```Kotlin
val mapOptions = MapOptions(
mapKey = "YOUR_TOMTOM_API_KEY",
mapStyle = styleDescriptor,
)
```
--------------------------------
### Get Last Known Location in Android
Source: https://developer.tomtom.com/maps/android/guides/location/create-your-own-provider
This code shows how to retrieve the last known GeoLocation from the LocationProvider. It handles cases where the location might not have been determined yet.
```java
val lastLocation = locationProvider.lastKnownLocation
```
--------------------------------
### Style Zoom Controls in XML
Source: https://developer.tomtom.com/maps/android/guides/map-display/ui-controls
Shows how to define styles for `ZoomControlsView` in XML, including setting visibility and custom zoom icons. This approach is useful for declarative UI setup.
```XML
Copy
```
```XML
1
```
```XML
2visible
```
```XML
3@drawable/ic_cafe
```
```XML
4start
```
```XML
5
```
--------------------------------
### Plan a Route with RoutePlanningOptions in Android
Source: https://developer.tomtom.com/maps/android/guides/routing/planning-a-route
Demonstrates how to create a RoutePlanningOptions object with itinerary, cost model, and alternative routes, then use it to plan a route asynchronously.
```Kotlin
val amsterdam = GeoPoint(52.377956, 4.897070)
val rotterdam = GeoPoint(51.926517, 4.462456)
val routePlanningOptions = RoutePlanningOptions(
itinerary = Itinerary(origin = amsterdam, destination = rotterdam),
costModel = CostModel(routeType = RouteType.Efficient),
vehicle = Vehicle.Truck(),
alternativeRoutesOptions = AlternativeRoutesOptions(maxAlternatives = 2),
)
```
--------------------------------
### Plan Route with Incremental Guidance - Java
Source: https://developer.tomtom.com/maps/android/guides/routing/planning-a-route
Demonstrates how to plan a route using the TomTom Routing API with incremental guidance enabled. It shows the creation of GeoPoint objects for origin and destination, setting the RouteInformationMode to FirstIncrement for faster planning, and initiating the route planning process.
```Java
val amsterdam = GeoPoint(52.377956, 4.897070)
val rotterdam = GeoPoint(51.926517, 4.462456)
val routePlanningOptions = RoutePlanningOptions(
itinerary = Itinerary(amsterdam, rotterdam),
mode = RouteInformationMode.FirstIncrement,
)
val result = routePlanner.planRoute(routePlanningOptions)
```
--------------------------------
### Execute Route Planning and Handle Callbacks in Android
Source: https://developer.tomtom.com/maps/android/guides/routing/planning-a-route
Shows how to call the planRoute method with the defined RoutePlanningOptions and implement the RoutePlanningCallback to manage success and failure responses.
```Kotlin
routePlanner.planRoute(
routePlanningOptions,
object: RoutePlanningCallback {
override fun onSuccess(result: RoutePlanningResponse) {
// YOUR CODE GOES HERE
}
override fun onFailure(failure: RoutingFailure) {
// YOUR CODE GOES HERE
}
override fun onRoutePlanned(route: Route) {
// YOUR CODE GOES HERE
}
},
)
```
--------------------------------
### Kotlin: TurnAroundWhenPossibleInstruction copy() and Destructuring
Source: https://developer.tomtom.com/maps/android/releases/latest
Illustrates the usage of the copy() method and destructuring declarations for the TurnAroundWhenPossibleInstruction class. This facilitates creating new instances with specific modifications or accessing its properties directly.
```Kotlin
val originalTurnAround = TurnAroundWhenPossibleInstruction(...)
val copiedTurnAround = originalTurnAround.copy()
val (instructionType, nextRoad) = originalTurnAround
```
--------------------------------
### Access Android Code Samples for Navigation SDK
Source: https://developer.tomtom.com/maps/android/introduction/whats-new
This snippet provides access to Android code samples demonstrating the offline functionality of the Navigation SDK. Users can visit the GitHub repository to explore these samples.
```text
Access Android code samples
```
--------------------------------
### Navigation: InstructionPhase toString Override
Source: https://developer.tomtom.com/maps/android/releases/versions/1
The `toString` method in `com.tomtom.sdk.navigation.guidance.InstructionPhase` can be overridden to provide more useful information by printing the name of the value.
```Kotlin
override fun toString(): String = "InstructionPhase(value=${name})"
```
--------------------------------
### Simplified Route Planner Creation
Source: https://developer.tomtom.com/maps/android/releases/latest
Provides simplified functions for creating `OfflineRoutePlanners` and `RoutePlanners` based on Self-Service guidelines. These functions streamline the initialization process for route planning.
```Kotlin
val offlineRoutePlanner = RoutePlanner()
val routePlanner = RoutePlanner()
```
--------------------------------
### Prefetching Configuration (Kotlin)
Source: https://developer.tomtom.com/maps/android/releases/latest
This Kotlin code snippet illustrates the use of `PrefetchingConfiguration` from the `com.tomtom.sdk.datamanagement.navigationtile` package. It shows how to configure the prefetch radius, lane tile requests, and area along the route, with these components now being generally available.
```Kotlin
import com.tomtom.sdk.datamanagement.navigationtile.PrefetchingConfiguration
// Example of creating PrefetchingConfiguration
val prefetchingConfig = PrefetchingConfiguration(
prefetchedAreaRadius = 5000, // Radius in meters
shouldRequestLaneTiles = true,
prefetchedAreaAlongRoute = true // Whether to prefetch areas along the route
)
// The components like prefetchedAreaRadius, shouldRequestLaneTiles, prefetchedAreaAlongRoute,
// and the constructor are now generally available.
```
--------------------------------
### Enable Location Updates in Android
Source: https://developer.tomtom.com/maps/android/guides/location/create-your-own-provider
This code snippet shows how to enable the location provider to start receiving location updates. It's a crucial step after setting the provider to ensure data flow.
```java
locationProvider.enable()
```
--------------------------------
### Initialize Reverse Geocoder (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/reverse-geocoding
This code demonstrates how to initialize the `ReverseGeocoder` interface using the `OnlineReverseGeocoder` implementation. You need your TomTom API key for this step.
```Kotlin
val reverseGeocoder: ReverseGeocoder = OnlineReverseGeocoder.create(context, "YOUR_TOMTOM_API_KEY")
```
--------------------------------
### Add and Configure a Route
Source: https://developer.tomtom.com/maps/android/guides/map-display/routes
Demonstrates how to add a route to the map with custom options including geometry, color, width, progress, and departure/destination markers. The `RouteOptions` class is used for configuration.
```Kotlin
val routeOptions = RouteOptions(
geometry = listOf(
GeoPoint(52.377956, 4.897070),
GeoPoint(51.377956, 4.997070),
GeoPoint(50.377956, 5.897070),
GeoPoint(52.377956, 5.897070)
),
color = Color.BLUE,
outlineWidth = 3.0,
widths = listOf(WidthByZoom(5.0)),
progress = Distance.meters(1000.0),
instructions = listOf(
Instruction(
routeOffset = Distance.meters(1000.0),
combineWithNext = false
),
Instruction(
routeOffset = Distance.meters(2000.0),
combineWithNext = true
),
Instruction(routeOffset = Distance.meters(3000.0))
),
tag = "Extra information about the route",
departureMarkerVisible = true,
destinationMarkerVisible = true
)
val route = tomTomMap.addRoute(routeOptions)
```
--------------------------------
### Get Current Camera Position - Android
Source: https://developer.tomtom.com/maps/android/guides/map-display/camera-and-animations
Retrieves the current camera position, which includes the map's location, zoom level, tilt, and rotation. This is useful for understanding the current view or for saving and restoring map states.
```Kotlin
val cameraPosition = tomTomMap.cameraPosition
```
--------------------------------
### Get Map Layers (Android)
Source: https://developer.tomtom.com/maps/android/guides/map-display/map-styles
Shows how to access the available map layers using the tomTomMap.layers property. This allows developers to inspect and potentially modify which map features are displayed, such as roads, points of interest, or traffic information.
```Kotlin
val layers = tomTomMap.layers
```
--------------------------------
### Create and Manage User Profile with Offline Personal Data (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/personalization/personal-data
Demonstrates how to initialize PersonalData, load a user profile, add a favorite location, and store the updated profile. This involves using the PersonalDataFactory, UserProfile, Place, GeoPoint, and Address classes. Ensure the user profile is stored to persist changes.
```Kotlin
val personalData: PersonalData = PersonalDataFactory.create(
context = context,
storageDir = File("path/to/personal/data"),
)
// Loading the user profile in memory.
var userProfile: UserProfile = personalData.loadUserProfile().value()
// Modifying the in-memory user profile.
userProfile.locations.create(
name = "Royal Home",
types = setOf(PersonalLocationType.Favorite),
place = Place(
coordinate = GeoPoint(
latitude = 52.373207,
longitude = 4.891391,
),
address = Address(
freeformAddress = "Royal Palace, Amsterdam, Netherlands",
),
),
)
// Storing the user profile.
userProfile = personalData.storeUserProfile(userProfile).value()
```
--------------------------------
### Request Parking Availability (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/search/dynamic-data
Shows how to request parking availability using the `ParkingDetailProvider`. It includes setting up the provider with an API key and handling the asynchronous response via callbacks for success and failure.
```Kotlin
parkingDetailProvider = OnlineDynamicDataProviderFactory.createParkingDetailProvider(
context,
"YOUR_TOMTOM_API_KEY",
)
parkingAvailabilityOptions?.let { options ->
parkingDetailProvider.requestParkingAvailability(
options,
object : ParkingAvailabilityCallback {
override fun onSuccess(result: ParkingAvailabilityResponse) {
// YOUR CODE GOES HERE
}
override fun onFailure(failure: SearchFailure) {
// YOUR CODE GOES HERE
}
},
)
}
```
--------------------------------
### Navigation: Signpost Copy Method Deprecation
Source: https://developer.tomtom.com/maps/android/releases/versions/1
The `copy()` method for the `com.tomtom.sdk.navigation.guidance.instruction.Signpost` class is deprecated. Use the constructor to create a copy of the Signpost instance.
```Kotlin
@Deprecated("Use constructor to create the copy.")
fun copy(exitNumber: Int? = this.exitNumber, exitName: String? = this.exitName, towardName: String? = this.towardName, icon: String? = this.icon, modifier: String? = this.modifier, distanceToNext: Int? = this.distanceToNext, streetName: String? = this.streetName, isRoundabout: Boolean = this.isRoundabout, roundaboutExitNumber: Int? = this.roundaboutExitNumber, roundaboutExitName: String? = this.roundaboutExitName, roundaboutTowardName: String? = this.roundaboutTowardName): Signpost = Signpost(exitNumber, exitName, towardName, icon, modifier, distanceToNext, streetName, isRoundabout, roundaboutExitNumber, roundaboutExitName, roundaboutTowardName)
```
--------------------------------
### Add Polyline to Map (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/map-display/overlays
Demonstrates how to create and add a polyline to the TomTom map using PolylineOptions. This includes setting coordinates, line colors, widths, outline colors and widths, and cap types for the start and end of the line.
```Kotlin
val lineColor = Color.rgb(0.2f, 0.6f, 1.0f)
val outlineColor = Color.rgb(0f, 0.3f, 0.5f)
val polylineOptions = PolylineOptions(
listOf(
GeoPoint(latitude = 52.33744437330409, longitude = 4.84036333215833),
GeoPoint(latitude = 52.3374581784774, longitude = 4.88185047814447),
GeoPoint(latitude = 52.32935816673911, longitude = 4.910078096170823),
),
lineColor = lineColor,
lineWidths = listOf(WidthByZoom(10.0)),
outlineColor = outlineColor,
outlineWidths = listOf(WidthByZoom(1.0)),
lineStartCapType = CapType.InverseDiamond,
lineEndCapType = CapType.Diamond,
)
val polyline = tomTomMap.addPolyline(polylineOptions)
```
--------------------------------
### Create SimulationLocationProvider with TimestampStrategy (Kotlin)
Source: https://developer.tomtom.com/maps/android/guides/location/simulation-location-provider
Demonstrates how to create an instance of `SimulationLocationProvider` using the `TimestampStrategy`. This strategy simulates location updates based on the time differences between consecutive `GeoLocation` objects, suitable for recorded traces.
```kotlin
val timestampStrategy = TimestampStrategy(locations = locations)
val simulationLocationProvider = SimulationLocationProvider.create(timestampStrategy)
```
--------------------------------
### Plan Initial Route with Alternative Routes (Android)
Source: https://developer.tomtom.com/maps/android/guides/routing/planning-alternative-routes
Demonstrates how to request alternative routes during initial route planning by setting `maxAlternatives` in `AlternativeRouteOptions`. The code snippet shows the creation of `GeoPoint` objects for origin and destination, configuring `RoutePlanningOptions` with `Itinerary` and `AlternativeRoutesOptions`, and initiating the route planning process.
```Java
val amsterdam = GeoPoint(52.377956, 4.897070)
val rotterdam = GeoPoint(51.926517, 4.462456)
val routePlanningOptions = RoutePlanningOptions(
itinerary = Itinerary(
origin = amsterdam,
destination = rotterdam,
),
alternativeRoutesOptions = AlternativeRoutesOptions(
maxAlternatives = 1,
),
)
val result = routePlanner.planRoute(routePlanningOptions)
```
--------------------------------
### Get Geometry IDs from Fuzzy Search Results
Source: https://developer.tomtom.com/maps/android/guides/search/find-a-location
This Kotlin code snippet demonstrates how to extract geometry IDs from the results of a fuzzy search. It iterates through the search results and maps each `SearchResult` to its `geometryId` if available, creating a list of geometry IDs.
```Kotlin
val geometries = fuzzySearchResponse.results.mapNotNull { it.searchResultId.geometryId }
```