Migrating from Mapbox GL JS to TomTom Maps SDK for Web
TomTom Developer Portal·Jul 16, 2020

Migrating from Mapbox GL JS to TomTom Maps SDK for Web

TomTom Developer Portal
TomTom Developer Portal
Jul 16, 2020 · 12 min read

If you're building a website that needs mapping and location capabilities, the TomTom Maps SDK for Web provides powerful, easy-to-implement traffic, routing, and search capabilities. Even if you've started an app on a different platform, it's easy to migrate to the TomTom Maps SDK. We'll show you how to migrate an existing MapBox GL JS app to use TomTom APIs in just a few minutes.


Once upon a time, creating maps was a huge challenge for web developers. Including any map at all was generally an exercise in creating a static map (an entire field of its own) and including it on the page. If you wanted an interactive map, you pretty much had to create your own GIS application entirely.

Today, location-based services like TomTom Maps SDK for Web and the TomTom location APIs have changed that by encapsulating the complexity of geospatial applications in easy-to-use services you can easily build into a website, without needing a boatload of geospatial know-how.


The following article walks through the construction of a simple Tom Tom application, along with a short example illustrating how the construction of the TomTom API is consistent with industry APIs to indicate how to port it from another mapping application, in this case the MapBox GL JS API.

The MapBox App

The following web application illustrates what a typical MapBox GL application might look like. The application lets the user navigate via longitude, latitude, and zoom levels to any point on Earth and see the coordinates and zoom level of the map. It also lets users assign markers with associated popups by clicking on the map while holding down the Alt (or Option) key.


Migrating this particular app to TomTom turns out to be surprisingly simple, especially since TomTom has ensured that the APIs involved are consistent with those found in other mapping applications, such as MapBox and Google Maps. If you're building a website that needs mapping and location capabilities, TomTom's services provide powerful, easy-to-implement traffic, routing, and search capabilities, and also provide SDKs for web and mobile development, making it very easy to integrate into your application or migrate from another mapping solution.

As with many services, the MapBox GL JavaScript library can be loaded directly from the web.

1<script src='https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.js'></script>
2<link href='https://api.mapbox.com/mapbox-gl-js/v1.8.0/mapbox-gl.css' rel='stylesheet' />

This also loads the CSS files. Once this is done, the base class msgbox1 is initialized, and the style of the map is set:

1mapboxgl.accessToken = <API_Token>;
2var map = new mapboxgl.Map({
3container: 'map',
4style: 'mapbox://styles/mapbox/streets-v9'

Styles in MapBox reference a different set of identifiers than Tom Tom, and can be seen in more details in the Map API's options.style section (https://docs.mapbox.com/mapbox-gl-js/api/).

Converting to a TomTom Maps SDK Application

To get started making this a TomTom Maps SDK for Web application, you’ll need an API key, or multiple if you’d like to separate each API and use a unique key for each one – this is up to you, but you can get by fine with just one.

To get a TomTom API key, create a new account (or log-in if you have an existing account) at the TomTom Developer portal, then click on the Dashboard tab. This will let you establish a new token if you have not done so. In general you will need only one, which should cover most basic TomTom services.

TomTom recommends that, rather than downloading the Maps SDK scripts and CSS for direct deployment, you should use the TomTom CDN to access this. Referencing the CDN version makes sure you will automatically use the most recent release to allow for bug fixes and performance improvements.

In this case, all we have to do is change the src URL to point to the TomTom Maps SDK (maps-web.min) and the linked stylesheet href for the CSS.

1<script src="https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.38.0/maps/maps-web.min.js"></script>
2<link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/5.x/5.38.0/maps/maps.css'>

Note that this runs the mapping code through the direct browser interface maps-web.min.js. If you are building the application for use with WebPack via nodejs, use maps.min.js, which conforms to the UDM standards, and then in your script import the tt object via an import statement:

1import tt from '@tomtom-international/web-sdk-maps'

This global variable tt contains the relevant class object model.

In addition to this, you need a key that determines how many maps can be deployed.

With this and the token you can then create a default map by setting up an HTML div and adding a script. In this particular case, the details for this were set up as a default data structure called initOptions, and this was then passed to a class constructor called MapApp (covered below) that wraps the TomTom tt.Map() class.

1<div id='map' style='width: 400px; height: 300px;'></div>
3const mapAPI = tt;
5let initOptions = {
6 key: 'apikey',
7 container: 'map',
8 style: 'tomtom://vector/1/basic-main',
9 center: [-122.01, 47.53],
10 zoom:10,
13let mapApp = new MapApp(initOptions);

The options object passed this way identifies the type of container, but also provides a namespace under the message protocol that indicates that this is a street map. This determines the feature set that gets displayed. A full listing of the protocols (covering vector views, satellite views, and day vs. night views) can be found under Map Styles in the Map Display API documentation.

The HTML for the TomTom version of the page is straightforward, having both a "map" ID and "map" class. The code for the interface is also straightforward: the first part holding the displays for showing longitude, latitude, and zoom, and the latter a display that will appear when the user alt-clicks on the map itself to specify a location. This is the same as the MapBox GL JS application.

1<div class="appContainer">
2 <div id='map' class="map" style="width:800px;height:600px;"></div>
3<div  class="interface">
4 <h1>The Map App</h1>
5 <p>Press Alt + mouse-down to add a marker to the map.</p>
6 <form>
7 <div>
8   <label for="lat">Latitude</label>
9   <span class="minVal">-90</span> <input value="0" id="lat"  type="range" min="-90" max="90" class="slider"/> <span class="maxVal">90</span>
10       <input value="0" id="latText" type="number" min="-90" max="90" />
11 </div>
12 <div>
13   <label for="lng">Longitude</label>
14   <span class="minVal">-180</span> <input value="0" id="lng"  type="range" min="-180" max="180" class="slider"/> <span class="maxVal">180</span>
15       <input value="0" id="lngText" type="number" min="-90" max="90" />
16 </div>
17 <div>
18   <label for="zoom">Zoom</label>
19   <span class="minVal">0</span> <input value="0" id="zoom"  type="range" min="0" max="20" class="slider"/> <span class="maxVal">20</span>
20       <input value="0" id="zoomText" type="number" min="0" max="20" />
21 </div>
22 </form>
23 <div id="addMarkerDialog">
24 <form method="dialog" id="addMarkerForm">
25   <div class="dialog">
26   <div class="dialogBody">
27     <div class="property">
28       <label>Marker Body</label>
29       <textarea id="message" placeholder="Enter popup text."></textarea>
30     </div>
31   </div>
32   </div>
33   <div>
34     <label for="color">Select a color</label>
35     <select id="color" value="">
36       <option value="" selected="selected">No Color Selected</option>
37       <option value="blue">Blue</option>
38       <option value="red">Red</option>
39       <option value="green">Green</option>
40       <option value="yellow">Yellow</option>
41       <option value="purple">Purple</option>
42     </select>
43   </div>
44   <div>
45     <label>Or select an icon</label>
47     <input src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/620300/travel-transport-hotel-vacation-holidays-tourist-tourism-travelling-traveling_147-512.png" type="image" class="icon" id="hotel"/>
48     <input src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/620300/cafe-512.png" type="image" class="icon" id="restaurant"/>
50     <input src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/620300/kindpng_229940.png " type="image" class="icon" id="coffee1"/>
51     <input src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/620300/9772.png " type="image" class="icon" id="coffee1"/>
52     <input value="" id="selectedImage" type="hidden"/>
53   </div>
54   <menu>
55     <button id="addMarkerCancelBtn">Cancel</button>
56     <button id="addMarkerConfirmBtn" value="default">Confirm</button>
57   </menu>
58   </div>

Of special note here are the four image input fields. They can be used to select an item as an image marker for the map and are actually used as the template for those icons. To add or change the icons, just add or change the associated input fields.

The script for working with the map is contained within two classes: one that handles the user interaction controls called MapApp and a second that builds the marker and its associated popup called MarkerPopup.These in turn wrap the corresponding Map, Marker, and Popup components defined for MapBoxGL.

1const mapAIP = tt;
3class MapApp {
4  constructor(initOptions){
5    tt.accessToken= initOptions.accessToken;
6    this.initOptions = initOptions;
7    this.map = new mapAPI.Map(initOptions);
8    this.markers = [];
9    let me = this;
10    this.latElt  = document.querySelector("#lat");
11    this.latElt.value = this.initOptions.center[1];
12    this.latTextElt  = document.querySelector("#latText");
13    this.latTextElt.value = this.initOptions.center[1];
14    this.lngElt = document.querySelector("#lng");
15    this.lngElt.value = this.initOptions.center[0];
16    this.lngTextElt = document.querySelector("#lngText");
17    this.lngTextElt.value = this.initOptions.center[0];
18    this.zoomElt = document.querySelector("#zoom");
19    this.zoomElt.value = this.initOptions.zoom;
20    this.zoomTextElt = document.querySelector("#zoomText");
21    this.zoomTextElt.value = this.initOptions.zoom;
22    this.addMarkerDialog = document.querySelector("#addMarkerDialog");
23    this.messageElt = document.querySelector('#message');
24    this.confirmBtn = document.querySelector('#addMarkerConfirmBtn')
25    this.cancelBtn = document.querySelector('#addMarkerCancelBtn')
26    this.colorSelect = document.querySelector('#color')
27    this.selectedImageElt = document.querySelector('#selectedImage');
28    document.querySelectorAll('.icon').forEach((elt)=>elt.addEventListener('click',evt=>{
29      me.selectedImageElt.value = evt.target.id;
30      me.colorSelect.value = "";
31    }))
32    this.activeMarker = {}
33    this.latElt.addEventListener("input", evt => me.update());
34    this.lngElt.addEventListener("input", evt => me.update());
35    this.zoomElt.addEventListener("input", evt => me.update());
36    this.latTextElt.addEventListener("input", evt => me.update());
37    this.lngTextElt.addEventListener("input", evt => me.update());
38    this.zoomTextElt.addEventListener("input", evt => me.update());
39    this.confirmBtn.addEventListener("click", evt => me.addMarkerPopup(evt));
40    this.cancelBtn.addEventListener("click", evt => me.closeMarkerPopup(evt));
41    this.map.on("drag", evt => {
42      let center = evt.target.transform._center;
43      this.latElt.value = center.lat;
44      this.latTextElt.value = center.lat;
45      this.lngElt.value = center.lng;
46      this.lngTextElt.value = center.lng;
47    });
48    this.map.on("zoom", evt => {
49      let zoom = evt.target.transform.zoom;
50      this.zoomElt.value = zoom;
51      this.zoomTextElt.value = zoom
52    })  
53    this.map.on("click", evt => {
54      if (evt.originalEvent.altKey && !evt.originalEvent.shiftKey) {
55        this.activeMarker = {}
56        console.log(evt);
57        this.activeMarker.lngLat = evt.lngLat;
58        this.activeMarker.zoom = evt.target.transform.zoom;       
59        this.addMarkerDialog.classList.add('visible');
60      }     
61    });
63  }
64  update(){
65    this.map.setCenter([this.lngElt.value,this.latElt.value]);
66    this.map.setZoom(this.zoomElt.value);
67  }
69  addMarkerPopup(){
70    console.log(this.activeMarker);
71    this.activeMarker.message = this.messageElt.value;
72    this.activeMarker.color = this.colorSelect.value;
73    console.log(`${this.selectedImageElt.value}`);
74    let baseElement = document.getElementById(`${this.selectedImageElt.value}`);
75    if (baseElement != null){
76      let imgNode = document.createElement("img");
77      imgNode.setAttribute("src",baseElement.getAttribute("src"));
78      imgNode.setAttribute("class",baseElement.className);
79      this.activeMarker.element = imgNode;
80    }
81    this.activeMarker.draggable = true;
82    this.markers.push(new MarkerPopup(this.map,this.activeMarker))
83    this.selectedImageElt.value = "";
84    this.closeMarkerPopup();
85  }
86  closeMarkerPopup(){
87    this.addMarkerDialog.classList.remove('visible');
88  }
91class MarkerPopup {
92  constructor(map,activeMarker) {
93    let options = {offset:[0,-40]};
94    this.popup = new mapAPI.Popup(options)
95      .setLngLat(activeMarker.lngLat)
96      .setText(activeMarker.message)
97      .addTo(map);
98    this.marker = new mapAPI.Marker({ 
99      color:activeMarker.color,element:activeMarker.element,
100      draggable:activeMarker.draggable })
101      .setLngLat(activeMarker.lngLat)
102      .setPopup(this.popup)
103      .addTo(map);
104  };

The TomTom map object specifies positions using LngLatLike objects, which can either be a LngLat() dedicated object, an object with lng and lat attributes, or an array in the form [lng,lat], where lng is the longitude in the range of -180 and 180 and lat is the latitude between -90 and 90.

Issaquah, a suburb of Seattle, has coordinates [-122.01, 47.53], and is used as the center point for the maps given here.

In addition to position, the maps make use of a zoom coordinate that can range from 0 (where the whole world is displayed) to around 23, where each tick represents a four times zoom in the number of tiles being displayed. In other words, a zoom of ten means that you are at a scale of 2^10 (or about 1000 times the resolution), for about 2^20 (c. one million) tiles.

Markers and popups are used to highlight individual points on the map. While not demonstrated here, it is possible to indicate a level of detail range determined by zoom where individual markers show up.

Popups are HTML div elements that appear relative to the markers when clicked or rolled over (depending upon options settings). The markers themselves default to SVG-based pointers that can be set to various colors (via the color attribute). It's also possible to set the icon to an HTML element such as an img element or an SVG element. Similarly, the popup can be set to a text field (illustrated here) or an HTML field.

In general, HTML should be avoided if the application has the potential for user interaction, as it becomes possible for someone to use it to take advantage of code injection as a way of hacking a server.

Note also the options variable passed to the Popup with the offset value. Popups are usually bound to entities, and at least with TomTom, the popup will usually appear at the same place as the base marker is anchored. By passing an offset as an [x,y] array of pixels, the popup bubble will appear relative to the marker's base, with an offset of [0,0] indicating they share anchor points. It's also possible to use the .setLngLat method on an offset, but as the map is zoomed, the marker and the popup positions will diverge in that case..

Finally, note the const declaration at the top. The MapAI const holds an instance of the tt object that provides the base class for operations, but, as will be shown below, there are advantages to using a variable by pointer here.

The CSS is similarly straightforward:

1.appContainer {
2 display:flex;
3 flex-direction:row;
6.map {
7 width:800px;
8 height:600px;
9 border:inset 2px gray;
12.interface {
13 padding:0.25in;
14 border:inset 2px gray;
18.dialog {
19 display:flex;
20 flex-direction:column;
21 font-family:Arial;
23.dialogHead {
24 position:absolute;
26 display:block;
27 height:32px;
28 margin:0;
29 width:100%;
30 left:0;
31 top:0;
32 background-color:navy;
33 color:white;
34 line-height:20px;
35 text-align:center;
36 font-family:Arial;
37 font-weight:bold;
39.dialogBody {
40 margin-top:32px;
43.dialogBody .property label {
44  display:block;
45 font-weight:bold;
48.dialogBody textArea {
49 width:200px;
50 height:120px;
53#addMarkerDialog {
54   display:none;
56#addMarkerDialog.visible {display:block;}
57.hide {display:none;}
58label {font-weight:bold;display:block}
59label:after {content:":"}
61.icon {max-width:64px;max-height:64px}

Once the classes have been defined, they need to be initialized:

1let initOptions = {
2 container: "map",
3 style: "tomtom://vector/1/basic-main",
4 zoom: 10,
5 center: [-122.01, 47.53],
6 accessToken: <TomTom_API_token>
9let mapApp = new MapApp(initOptions);

This associates the map object with the element with id of the same name, sets the map style as described above, determines the beginning zoom and center of the map, and passes the access token to the map object to allow for service call access.


Wrapping Up

Converting from MapBoxGL to TomTom is straightforward. If you're comfortable with the MapBox GL interfaces, then TomTom conversions should be quite easy, and include with them greater robustness of the TomTom products.

Lastly, if you're looking to switch from Google, check out this quick video tutorial on migrating from Google Maps to TomTom Maps APIs and SDKs:

Get the developer newsletter.
No marketing fuff. Tech content only.

* Required field. By submitting your contact details to TomTom, you agree that we can contact you about marketing offers, newsletters, or to invite you to webinars and events. We could further personalize the content that you receive via cookies. You can unsubscribe at any time by the link included in our emails. Review our privacy policy.