Sorry, you need to enable JavaScript to visit this website.

Documentation

Documentation

Map initialization

The main class with represents a Map is a MapView. MapView is wrapped by MapFragment.
To display map, MapFragment needs to be attached to layout.

The basic steps for adding a map are:

  1. Follow steps described in "Getting started" section.

  2. Add MapFragment to your Activity (either using the code or layout
    file).

  3. Implement the OnMapReadyCallback and use onMapReady method to get
    the TomtomMap object.

  4. Use the TomtomMap object to set the map properties (e.g. map mode,
    tiles types).

OnMapReadyCallback:

import androidx.annotation.NonNull;

/**
 * Callback interface executed when the map is ready to be used.
 * The instance of this interface is set to {@link MapFragment},
 * and the {@link OnMapReadyCallback#onMapReady(TomtomMap)} is triggered
 * when the map is fully initialized and not-null.
 */
public interface OnMapReadyCallback {
    /**
     * Called when the map is ready to be used.
     */
    void onMapReady(@NonNull TomtomMap tomtomMap);
}

 

Adding the MapFragment to XML file:

<fragment
    android:id="@+id/map_fragment"
    android:name="com.tomtom.online.sdk.map.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

 

Sample implementation of the OnMapReadyCallback:

_

private final OnMapReadyCallback onMapReadyCallback =
        new OnMapReadyCallback() {
            @Override
            public void onMapReady(TomtomMap map) {
                //Map is ready here
                tomtomMap = map;
                tomtomMap.setMyLocationEnabled(true);
                tomtomMap.collectLogsToFile(SampleApp.LOGCAT_PATH);
            }
        };
private val onMapReadyCallback = OnMapReadyCallback { tomtomMap ->
    val mapPaddingVertical = resources.getDimension(R.dimen.map_padding_vertical).toDouble()
    val mapPaddingHorizontal = resources.getDimension(R.dimen.map_padding_horizontal).toDouble()

    tomtomMap.uiSettings.currentLocationView.hide()
    tomtomMap.setPadding(mapPaddingVertical, mapPaddingHorizontal,
        mapPaddingVertical, mapPaddingHorizontal)
}

MapView initialization.

In some cases, it may be required to use 'MapView' directly, instead of having 'MapFragment'.
In such a case, you need to pass lifecycle events to 'MapView', as shown below:

@Override
/** @inheritDoc */
public void onStart() {
    super.onStart();
    mapView.onStart();
}

@Override
/** @inheritDoc */
public void onResume() {
    super.onResume();
    mapView.onResume();
}

@Override
/** @inheritDoc */
public void onPause() {
    mapView.onPause();
    callbackContainer.removeAllCallbacks();
    super.onPause();
}

@Override
public void onStop() {
    mapView.onStop();
    super.onStop();
}

@Override
public void onDestroy() {
    mapView.onDestroy();
    super.onDestroy();
}

 

When using Maps SDK for Android, it is required that TomTom logo is always visible.
By default, TomTom logo is located at the bottom left corner of the map.
However, you can easily customise its position to meet your app design by define LogoView
style in style.xml in your app.

Sample use case 1: Your app has a bottom panel which covers the TomTom logo and you need to place the logo in top right corner.
To change TomTom logo’s position:

<style name="LogoView" parent="BaseLogoView" >
    <item name="android:layout_gravity">bottom|left</item>
</style>

 

Map background color

It is possible to change the default color of the Map’s background during initialization.
To achieve that there are four options:

  • Passing the param during MapView initialization at xml:

<com.tomtom.online.sdk.map.MapView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:mapBackgroundColor="#0000ff"/>
  • Passing the param during MapFragment initialization at xml:

<fragment
    android:id="@+id/map_fragment"
    android:name="com.tomtom.online.sdk.map.MapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:customMapBackgroundColor="#0000ff"/>
  • Setting the mapBackgroundColor property after MapFragment creation at code:

val mapFragment = MapFragment.newInstance()
mapFragment.setMapBackgroundColor(Color.GREEN)
supportFragmentManager.beginTransaction()
            .replace(R.id.mapContainer, mapFragment)
            .commit()
  • Setting it globally by overriding:

style:

<style name="MapBackgroundStyle">
    <item name="android:background">#0000ff</item>
</style>

color:

<color name="defaultMapSurfaceColor">#0000ff</color>

Traffic flow tiles

The Maps SDK provides traffic flow overlay for both raster and vector map tiles. It is up to the user of the API to ensure that the type of traffic flow overlay matches the type of map tiles.

Traffic flow can show different information depending on selected mode:

  1. absolute - free-flow speed.

  2. relative (default) - speed relative to free-flow.

  3. relative-delay - speed relative to free-flow, but only when different.

  4. reduced-sensitivity - speed relative to free-flow, but with wider speed ranges.

Traffic incident tiles

Maintaining the currency of traffic incident tiles

Traffic incident data provided as map tiles by the Vector Incident Tiles and Raster Incident Tiles services is updated periodically to reflect the current state of traffic as closely as possible. It might happen that the traffic data changes between two requests to the service. In this situation, always requesting the most recent data may lead to inconsistencies in the visual representation of traffic - adjacent tiles may show traffic in different states. The traffic incident tile services provide a way to synchronize tiles between requests. If the ID of a traffic model is supplied in a request’s URL, the traffic model specified by that ID is used to fulfill the request. The Traffic Incident Viewport service provides the ID of the most recent traffic model shared between all tiles within provided viewport.

The Maps SDK automatically synchronizes traffic incident tiles displayed on the map and maintains their currency by periodically requesting traffic model ID for the current viewport.

The Maps SDK requests current traffic model ID from the Traffic Incident Viewport service every 30 seconds as long as the visibility of at least one traffic incident layer is set to true. If the new ID and the current one are different, new traffic incident tiles are requested from the respective service. All regular charges apply.

Online resources caching

To display the map some external resources are needed by the map renderer:
map style and map tiles.

Map style itself (.json file describing map layers display properties and rendering order)
and assets needed by the style are bundled with SDK library.
Style assets include sprites (sets of icons) displayed on the map and fonts.

When the map viewer is focused at particular spot, map tiles provided by
remote online server are needed to display the map. When a part of the map
is displayed for the first time, needed tiles are downloaded from the server.
Resources downloaded from the server are stored (cached) in an offline
database for further use. The server communicates maximum tile resource lifetime
by means of "Cache-Control" HTTP header. Expiration time
is stored in the offline database together with the tile resource.
If a tile resides in the cache it can be displayed even if internet
connection is not available. When the object in the cache expires, the server is
asked again about the object. If a newer version of the object is available,
it is downloaded and
the cache contents are refreshed. If the old resource is still valid, its lifetime
is prolonged.
Cache size is limited to 50MB of disk space. When the limit is reached,
least recently used tile resources are discarded.

Map Layers

The Maps SDK uses JSON documents (styles) defining the sources of data to be shown on the map and its appearance. Styles are compliant with Mapbox Style Specification.

Layers

The layers property of a style is an array of all the layers the style defines. Each element of the array contains all the information needed to render a layer. Note that a single element of a map, such as a road, may consist of several layers. Among the properties of a layer, two are of particular interest in this context:

  • source - the name of the source of data for the layer. Corresponds to a child of the sources property.

  • source-layer - the name of a layer in a vector tile source. Corresponds to an element of a vector tile.

Sources

Sources are defined as properties of the sources root property of a style. The structure of a source depends on its type. The style used in the Maps SDK contains three types of source:

  • vector - vector map and traffic tiles.

  • raster - raster map and traffic tiles.

  • geojson - additional elements such as chevron, gps inaccuracy radius indicator, etc.

Source layers

The source layer property of a layer is mandatory for all layers of the vector type. It defines the element of a vector tile (also called a layer) which is the source of data for this layer.

As noted in the Layers section, there are elements of the map that consist of multiple layers. The layers that constitute such element might refer to the same source layer. For instance - the visual representation of a minor local toll road comprises 11 layers - one for the main part, one for the outline, another one for a road that goes through a tunnel, etc.

Check the Maps API Documentation for a complete list of vector layer sources (layers in a vector tile) used in the SDK.

Default style

Layer groups in the default style

The default style, delivered with the SDK, contains the following layer groups (background to foreground):

  1. Background - color and pattern displayed in places where there is no other map data.

  2. Vector map – baseline tile layer in vector format.

  3. Raster map - baseline tile layer in raster format.

  4. Raster overlay for hybrid maps - streets, labels and icons on transparent background.

  5. Traffic flow - raster and vector traffic flow tile overlays.

  6. Traffic incidents - raster and vector traffic incident tile overlays.

  7. Routes - planned and alternative routes.

  8. Vector map labels and icons – rendered on top of most other layers for better readability.

  9. GPS inaccuracy indicator - circle indicating the GPS inaccuracy area.

  10. Position indicator - static location marker.

  11. Chevron - animated location marker.

Custom style

You can change the appearance of the map by providing a JSON document (style)defining the sources of data to be shown on the map and its appearance. A style has to:

A basic style is provided as a part of the Cumstom Style Resources package.

Styles compliant with Mapbox Style Specification can be edited using style editors like maputnik. Before a style can be edited in maputnik:

  • Service key placeholders have to be replaced with actual service keys.

  • Sprite and glyph locations have to be replaced by ones that can be reached by maputnik.

  • TomTom-specific tags have to be removed from tile source links or replaced with default values.

  • (Optional) Visibility of layers can be altered to your preferences.

All these changes, with the exception of layer visibility, have to be reverted before the modified style can be used with the SDK. Custom Style Resources contain a Python script - convertStyle.py - which simplifies this process. Detailed usage instructions can be found in a dedicated section below.

Layer sets

The SDK uses the concept of a layer set to refer to a group of layers. A layer set consists of all layers using the same source. Layer sets listed in Table 1 are required for the SDK to function. If any of these layer sets are absent or do not meet the requirements mentioned below, they will be replaced with default layer sets created at runtime.






Table 1. Mandatory layer sets
Map view element Default source name Required layer type Required layer count Source type

Route polyline

tomtom-active-route

line

2

GeoJSON

Route start icon

tomtom-start-route

symbol

1

GeoJSON

Route end icon

tomtom-end-route

symbol

1

GeoJSON

GPS inaccuracy radius

tomtom-gpsradius

circle

1

GeoJSON

Position indicator

tomtom-position

symbol

1

GeoJSON

Vehicle icon

tomtom-chevron

symbol

1

GeoJSON

Two layers for route polyline define the outline and fill styles. Two layers for chevron, GPS radius and position define the styles of two versions of associated objects - normal (active) and dimmed (inactive).

There is a number of layer sets that are important, but not strictly required. They are responsible for providing style and data sources for maps - vector and raster, traffic flow and incidents as well as hybrid overlay. These sets will not be replaced by default ones at runtime.

Source URIs for map layer sets have fixed format - they contain placeholders for API keys and optional parameters. It is not recommended to change them.

Raster tile size

The SDK offers 256x256 px and 512x512 px raster tiles. By default, the larger tiles are used. The size of tiles can be modified by setting the tileSize parameter in the url of raster sources to either 256 or 512.

Style API

When your custom style is ready, place the JSON file in the /assets/styles/ directory in your Android Studio project or upload it to an online location that your application will be able to access. You can then use your new style in your application.

Even though online style locations are supported, glyphs and sprites have to be stored locally.

Sample use case 1: You want to display a night-themed map with inverted logo colors at night or while in a tunnel.

_

tomtomMap.getUiSettings().setStyleUrl("asset://styles/night.json");
tomtomMap.getLogoSettings().applyInvertedLogo();
tomtomMap.uiSettings.setStyleUrl("asset://styles/night.json")
tomtomMap.logoSettings.applyInvertedLogo()

Optionally, there is a possibility to load style directly from json text:

_

String styleJson = [...];
tomtomMap.getUiSettings().setStyleJson(styleJson);
val styleJson: String = [...]
tomtomMap.uiSettings.setStyleJson(styleJson)

Sample use case 2: You want to switch back to basic style for map and logo.

_

tomtomMap.getUiSettings().setStyleUrl("asset://styles/mapssdk-default-style.json");
tomtomMap.getLogoSettings().applyDefaultLogo();
tomtomMap.uiSettings.setStyleUrl("asset://styles/mapssdk-default-style.json")
tomtomMap.logoSettings.applyDefaultLogo()

IMPORTANT: Reloading style is an asynchronous operation. You need to ensure that no method modifies the style before this operation is done.
TomtomMapCallback.OnMapChangedListener.onDidFinishLoadingStyle is called when reloading the
style is finished. An OnMapChangedListener can be registered using TomTomMap.addOnMapChangedListener.



image

Basic style

image

Custom night style

Using convertStyle.py

The convertStyle.py script is distributed as a part of the Cumstom Style Resources bundle. It can be executed with one of two commands: 'maputnik' and 'tomtom'. When executed with the 'maputnik' command, it replaces TomTom-specific elements of the base style (-b|--base parameter) with values provided in script’s parameters or in Info.plist or AndroiManifest.xml. when executed with the 'tomtom' command, it reverts changes related to TomTom-specific elements while leaving user’s modification intact.

For the script to work properly, the same base file has to be used for both conversions.
Detailed usage instructions
python2 convertStyle.py <common parameters> <command=maputnik|tomtom> <command-specific parameters>

# All parameters are required unless specified otherwise

common parameters:
  -w WDIR, --wdir WDIR  Working directory. Root of relative paths.
                        [optional, default = "."]
  -S, --silent          Silent mode. No messages will be printed.
  -b BASE, --base BASE  Path to the base for the new style.
  -o OUTPUT, --output OUTPUT
                        Path to the output file.

commands:
    maputnik            Convert a base style so that it can be edited in
                        maputnik.
    tomtom              Convert a style edited in maputnik so that it works
                        with your application using TomTom SDK.

maputnik parameters:
  -k KEYS, --keys KEYS  Path to Info.plist or AndroiManifest.xml.
  -s SPRITES, --sprites SPRITES
                        Online location of sprites.
  -g GLYPHS, --glyphs GLYPHS
                        Online location of glyphs.
  -v {all,none,intact,predefined}, --visibility {all,none,intact,predefined}
                        Change visibility of layers. 'intact' leaves the base
                        style's settings intact, 'predefined' makes vector
                        layers visible and all other layers invisible.
                        [optional, default = "predefined"]

tomtom parameters:
  -e EDITED, --edited EDITED
                        Path to the style edited in maputnik.
Sample workflow
  1. Upload glyphs and sprites to an online location accessible by maputnik.

  2. Use convertStyle.py to create a style that can be edited in maputnik.

    python2 convertStyle.py -b mapssdk-default-style.json -o my_style_prepared_for_maputnik.json maputnik -k path/to/app/AndroiManifest.xml -g http://link.to.glyphs.com -s http://link.to.sprites.com
  3. Upload my_style_prepared_for_maputnik.json to maputnik.

  4. Edit the style in maputnik.

  5. Export the style in maputnik, saving it as my_style_exported_from_maputnik.json.

  6. Use convertStyle.py to prepare the style edited in maputnik to for use with TomTom SDK.

    python2 convertStyle.py -b mapssdk-default-style.json -o my_style_prepared_for_sdk.json tomtom -e my_style_exported_from_maputnik.json

You are here