Build Different

Building Embedded TomTom Maps with HTML Web Components and JavaScript

Shannon Stroud
Oct 11, 2019 • Last edit on Feb 11, 20202 min read
The word code on a laptop.

Web Components

Producing reusable components has always been one of the pillars of professional software engineering. For the web this has been especially hard — changing paradigms, frameworks, and libraries have made the situation more complicated than necessary. One of the potential solutions to this problem are Web Components. Using Web Components, we can easily create a reusable map component based on the TomTom Maps SDK for Web that can be dropped in when we need.

Web Components are an HTML standard that provide a great way to create reusable components that will work nicely with any web framework — or no framework at all. With Web Components, you can create a map component that’s easy to plug into any web page.

This article will show how to embed a map in a Web Component using TomTom JavaScript Maps SDK for Web.

What are Web Components?

Web Components refers to a set of browser capabilities and APIs to allow creating reusable components using HTML, CSS, and JavaScript. The capabilities and APIs include things such as Shadow DOM, custom elements, CSS scope, HTML templates, and more recent ECMAScript features.

Shadow DOM is the structure that is used inside a custom element. It is pretty much separated from the "real" DOM, but can be accessed from the hosting custom element. Usually, we will construct a Shadow DOM from some kind of template. Ideally, we use the HTML template element for such constructions (together with some established APIs such as cloneNode).

In a nutshell Web Components would be used like any other HTML component, like writing <my-element my-attr="foo">This is the content</my-element> in the HTML source code. In this example we use a Web Component called my-element with some attribute (my-attr) and content. The dashed name is a convention that should be respected as "real" HTML elements will never have a hyphen in their name. Thus this convention prevents potential conflicts.

Statically, such as from the HTML source code alone, such custom elements would be pretty much useless. Instead, we can give them some life by using JavaScript to define their behavior. The magic for this lies in the define API of the customElements object.

The define method takes two parameters: the name of the custom element and its DOM implementation. The latter is usually a class deriving from the respective parent. In case of uncertainty, the super class is most likely HTMLElement.

2 'my-element',
3 class extends HTMLElement {
4 constructor() {
5 super();
6 }
8 connectedCallback() {
9 //Do something once connected
10 }
11 },

The connectedCallback can be used to do some initial setup actions. There are more methods that can be used to hook into the lifecycle of (custom) components, but for now this one is sufficient.

To use Web Components in recent browsers, we don't need to do anything. The support for all given technologies has been present in most browsers for quite a while. Nevertheless, for older browsers — most notably those without any immediate update possibility such as older versions of Internet Explorer — a set of polyfills exists.

In general, we are free to select which polyfills to use. In the simplest case we just apply the full bundle of polyfills that only supplies the functionality that is required. The full bundle can be installed with:

npm install @webcomponents/webcomponentsjs

The installed package can either be used directly from some JavaScript module (bundled via Webpack) or referenced as a side-bundle from the HTML pages where Web Components are actively used.

The necessary HTML looks like:

<script src="node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>

Now that we know the basics of Web Components, let's build something useful with them!

Building a TomTom Maps Web Component

Let's just build a map component using the TomTom Maps SDK for Web that can be used to display a mapped location.

For that we need to start by registering as a developer on the TomTom developer portal. This will give us an API key that we can use later for accessing the Map Display API.

After we registered successfully, we should also download the latest version of the TomTom Maps SDK for Web. This can be found at the Maps SDK for Web Downloads website.

The basic skeleton for our new web component tt-map is a file called tt-map.js. In this file we start with the following boilerplate code:

1const template = document.createElement('template');
2template.innerHTML = `
3 <div id="map"></div>
7 'tt-map',
8 class extends HTMLElement {
9 constructor() {
10 super();
11 console.log('constructed!');
12 }
14 connectedCallback() {
15 console.log('connected!');
16 }
18 disconnectedCallback() {
19 console.log('disconnected!');
20 }
22 attributeChangedCallback(name, oldVal, newVal) {
23 console.log(`attribute "${name}" changed!`);
24 }
26 adoptedCallback() {
27 console.log('adopted!');
28 }
29 },

The boilerplate gives us full access to the lifecycle and some useful debugging output. We also start with a template element that contains some div. We will now use this template element to construct the Shadow DOM.

Using the TomTom Maps SDK for Web

Assuming we placed the TomTom Maps SDK for Web in the same folder as our new tt-map.js file, we can just go ahead and load the JavaScript. Loading the JavaScript requires an explicitly created script element. We could either do this via a bundler (merging together the TomTom Map SDK for Web script and our custom element source code) or load the TomTom Map SDK script explicitly. In this tutorial we will do the latter.

Essentially, the code for loading the script boils down to:

const ttscript = document.createElement('script');
ttscript.src = './tomtom.min.js';

The most important part is missing though — we still need to connect it to the DOM. In our case we have to do this via the Shadow DOM, but the API call (appendChild) will be the same as with the "real" DOM.

In the constructor of our custom element we call:

1this._shadowRoot = this.attachShadow({ mode: 'open' });

Once the JavaScript loaded we want to set up the map component. For this we can use the onload handler.

1ttscript.onload = () => {
2 const map = this._shadowRoot.querySelector('#map');
3, {
4 key: '<your-api-key>',
5 });

Remark: Please use your own API key here. Other API keys may be revoked, blocked, or unsuitable for the tasks that you want to fulfill.

Customization Possibilities

We may want to bring in some additional possibilities for customization. As an example, using the custom elements in a call such as this:

<tt-map locale="de-DE"></tt-map>

Specifying the de-DE locale gives us the map with German labels. To transport the attribute locale into the TomTom SDK options, we need to change the constructor as follows:

1constructor() {
2 super();
3 const language = this.getAttribute('locale') || 'en-GB';
4 const ttscript = document.createElement('script');
5 ttscript.src = './tomtom.min.js';
6 ttscript.onload = () => {
7 const host = this._shadowRoot.querySelector('#map');
8 const map =, {
9 key: 'LZhuGBLl7Uw22kPxtEI2AEUNUscmqBnp',
10 language,
11 });
12 };
13 this._shadowRoot = this.attachShadow({ mode: 'open' });
14 this._shadowRoot.appendChild(template.content.cloneNode(true));
15 this._shadowRoot.appendChild(ttscript);

If we want to add a simpler marker, we would just use the TomTom API marker function. This is split in two parts: creating the marker and adding it to the map:

tomtom.L.marker([48.1375019, 11.6865543]).addTo(map)

Consequently, to keep the possibility of adding markers to the map open, we should actually provide some nice API abstraction using custom elements on top of it.

Before we introduce an API abstraction for markers, let's take care of two essential map features:

  • defining the center of the map ("mapped location") and
  • setting the zoom level

For both of these settings we use attributes (center and zoom), which are then mapped by us to the respective TomTom Map SDK API calls (setView and setZoom respectively) within the constructor of the custom element.

1const zoom = this.getAttribute('zoom');
2const center = this.getAttribute('center');
4if (zoom) {
5 map.setZoom(+zoom);
8if (center) {
9 map.setView(center.split(',').map(m => +m));

This also brings us to the topic of changing attributes. Some of the introduced attributes may be immutable, such that the initial setting cannot be changed. However, others such as the center and zoom should be mutable and reflect their value in the displayed map as expected.

Luckily, we've already seen in the boilerplate that attributeChangedCallback may be available to help us out here. Furthermore, we need to notify which attributes to observe using a static observedAttributes field:

1class extends HTMLElement {
2 // ...
3 static observedAttributes = ['zoom', 'center'];
6 attributeChangedCallback(name, oldVal, newVal) {
7 if ( && oldVal !== newVal && typeof newVal === 'string') {
8 switch (name) {
9 case 'zoom':
10 return;
11 case 'center':
12 return',').map(m => +m));
13 }
14 }
15 }

Now that we’ve set center and zoom,, we could introduce the abstraction previously mentioned and add custom elements.


Besides the ability to receive notifications, such as about changed attributes, we may also want to emit events for somebody to receive, potentially including custom events.

The map instance in the TomTom Map SDK offers quite a few events we can use to listen for changes and emit a custom event ourselves. The code for the handler can be as simple as:

1const handler = () => {
2 const event = new CustomEvent('change', {
3 detail: {
4 zoom:,
5 center:,
6 },
7 });
8 this.dispatchEvent(event);

Here we create a new instance of a CustomEvent with type set to change. Users of tt-map can just use addEventListener('change') to register a handler.

But when are we emitting this change event? Let's start simple with changes to the zoom and center of the map.'zoom', handler);'moveend', handler);

Great! Now only the question with the markers is left.

For markers we can just provide another custom element called tt-map-marker. We then use standard techniques from object-oriented programming to call method on that custom element called onMapReady. This name was freely chosen.

Iterating through all children of the tt-map instance will lead to probing the specific method, which will then be called with the instantiated map component. At this point the custom element can choose what to do with the map in case of the marker it will just place a marker there.

The full JavaScript file now looks as follows:

1const template = document.createElement('template');
2template.innerHTML = `
3<link href="./map.css" rel="stylesheet">
5:host {
6 width: 100%;
7 height: 100%;
8 display: block;
10content {
11 width: inherit;
12 height: inherit;
14#map {
15 width: 100%;
16 height: 100%;
19<content><div id="map"></div></content>
22function getLatLng(val) {
23 return val.split(',').map(m => +m);
27 'tt-map-marker',
28 class extends HTMLElement {
29 static observedAttributes = ['position'];
31 onMapReady(map) {
32 = map;
33 this.attributeChangedCallback('position', undefined, this.getAttribute('position'));
34 }
36 attributeChangedCallback(name, oldVal, newVal) {
37 if ( && oldVal !== newVal && typeof newVal === 'string') {
38 switch (name) {
39 case 'position':
40 return tomtom.L.marker(getLatLng(newVal)).addTo(;
41 }
42 }
43 }
44 },
48 'tt-map',
49 class extends HTMLElement {
50 static observedAttributes = ['zoom', 'center'];
52 constructor() {
53 super();
54 const ttscript = document.createElement('script');
55 ttscript.src = './tomtom.min.js';
56 ttscript.onload = () => {
57 const host = this._shadowRoot.querySelector('#map');
58 const zoom = this.getAttribute('zoom');
59 const center = this.getAttribute('center');
60 =, {
61 key: 'LZhuGBLl7Uw22kPxtEI2AEUNUscmqBnp',
62 language: this.getAttribute('locale') || 'en-GB',
63 zoomControl: this.hasAttribute('zoom-control'),
64 panControl: this.hasAttribute('pan-control'),
65 zoomsliderControl: this.hasAttribute('zoomslider-control'),
66 traffic: this.hasAttribute('show-traffic'),
67 });
69 this.attributeChangedCallback('zoom', undefined, this.getAttribute('zoom'));
70 this.attributeChangedCallback('center', undefined, this.getAttribute('center'));
72 const handler = () => {
73 const event = new CustomEvent('change', {
74 detail: {
75 zoom:,
76 center:,
77 },
78 });
79 this.dispatchEvent(event);
80 };
82'zoom', handler);
83'moveend', handler);
85, child => {
86 if (typeof child.onMapReady === 'function') {
87 child.onMapReady(;
88 }
89 });
90 };
91 this._shadowRoot = this.attachShadow({ mode: 'open' });
92 this._shadowRoot.append(template.content.cloneNode(true), ttscript);
93 }
95 attributeChangedCallback(name, oldVal, newVal) {
96 if ( && oldVal !== newVal && typeof newVal === 'string') {
97 switch (name) {
98 case 'zoom':
99 return;
100 case 'center':
101 return;
102 }
103 }
104 }
105 },

Sample Application

Let's use our Web Component on a demo website. The HTML code is as simple and straightforward as the following one:

1<!doctype html>
2<meta charset=utf8>
3<title>TomTom Web Component Sample</title>
5html, body {
6 padding: 0;
7 margin: 0;
8 width: 100%;
9 height: 100%;
11body {
12 display: flex;
13 flex-direction: row;
15body > div {
16 flex: 1;
17 height: 100%;
19.container {
20 padding: 1em;
25 <div class="container">
26 <h1>TomTom Map SDK</h1>
27 <h2>Web Component Sample</h2>
28 <p>On the right you see some variations of the map control.</p>
29 </div>
32 <tt-map locale="en-GB" zoom-control></tt-map>
35 <tt-map locale="de-DE">
36 <tt-map-marker position="48.1375019, 11.6865543"></tt-map-marker>
37 <tt-map-marker position="40.0375019, 8.6865543"></tt-map-marker>
38 </tt-map>
41 <tt-map center="52.379189, 4.899431" id="map" zoom="12" zoom-control></tt-map>
43<script src="tt-map.js"></script>
45document.querySelector('#map').addEventListener('change', console.log);

The tt-map and tt-map-marker components comes from the referenced JavaScript file with the same content as seen earlier.

Opening the demo website gives us a simple four column layout. We re-use our map three times on the same page, just with different settings to see the difference.


Most importantly, we are fully flexible and framework agnostic when it comes down to using this component. All the dependencies (the CSS and JavaScript coming from the TomTom Maps SDK for Web) are already referenced within the component. As an example, using the #map selector within our HTML document will not result in any conflict with the #map selector used within the Shadow DOM that is contained in our Web Component.


Using Web Components can help us to finally build some reusable code that just works on the web - independent of any specific UI library or framework.

The possibilities with Web Components are enormous. The component we just built can be used on multiple pages for multiple use cases. Examples include a map marker, route navigation, or other map related duties.

More learning resources can be found at:

What will you build? Share your project with us on the TomTom Developer Forum.

Get the developer

No marketing fuff. Tech content only.
Thanks for contacting us

We will reach out to you soon.
Blog cards
tomtom tech news