Adding TomTom Maps to a Svelte App
TomTom Developer Relations·Aug 10, 2021

Adding TomTom Maps to a Svelte App

TomTom Developer Relations
Aug 10, 2021 · 6 min read

Enhancing your Svelte apps with interactive maps is quick and easy. Learn how to add a map to your app, center the user's current location, and link the location and chosen destination, using the TomTom Maps SDK and a little bit of JavaScript.

Adding TomTom Maps to a Svelte App

Adding maps to a web application improves user experience dramatically. Maps help your user find a location, plan a route, avoid traffic, see route progress, visualize boundaries, and so much more. They’ve become increasingly popular web app features through the rise of location-embed services.

Although maps may seem complex, it’s surprisingly easy to integrate maps into web apps using client-side libraries from TomTom. Front-end developers need effective and efficient options. TomTom Maps make adding interactive maps to Svelte apps a breeze, making them our ideal choice.

In this article, we’ll demonstrate how to add TomTom maps into a Svelte web application. We'll explore how to install the map SDK library, initialize it, and manipulate the map. To follow along, you should know JavaScript and be familiar with Svelte.

Setting Up

To create a Svelte app, first ensure you have Node.js installed on your computer. You can check for Node.js by typing the following command into your terminal:

1node -v

If not, simply go to the Node.js website to download the latest version.

Also, you’ll need to install the degit library so you can clone the Svelte template:

1npm install -g degit

When that finishes, we can get started with our Svelte app by creating an empty folder and cloning the template into our project named “tomtom":

1npx degit sveltejs/template tomtom       

Then, we go to our project folder on the terminal:

1cd tomtom

Now that we’ve set it up, we can install our project’s dependencies:

1npm install

We then run the Svelte app with:

1npm run dev

Installing the TomTom Library

To use TomTom’s search and route services, we first need to install TomTom Maps SDK. Use this command to install this library:

1npm i @tomtom-international/web-sdk-maps

To use the services in your app, register as a TomTom developer. You get thousands of free requests daily, even for commercial apps. You can simply pay as your app grows and expands.

When you register a developer account, you get an API key. Take note of the API key, because we’ll get back to it shortly.

Building the App

We’re building an app that initializes with a real-time map. Then, within that map, we can set the latitude and longitude of a start location and destination. The map will zoom in on that location, drawing a line between the two points. You can check out the demo on CodeSandbox.


First, to start building our app, let’s import the library and its default stylesheet into our component by adding them to the script tag. We also need to import onMount into our component so we can initialize our map when the component mounts on the Document Object Module (DOM):

1import tt from "@tomtom-international/web-sdk-maps";
2import '@tomtom-international/web-sdk-maps/dist/maps.css'
3import { onMount } from "svelte";

Then, we need to add the variables we’ll use in the app. The zoom variable selects the level of zoom we want on the map. The longitude and latitude are the initial longitude and latitude that the map displays when it loads.

1import tt from "@tomtom-international/web-sdk-maps";
2import '@tomtom-international/web-sdk-maps/dist/maps.css'
3import { onMount } from "svelte";

We’ll bind these variables directly with their <input/> element, so our app is always in sync when we change anything.

Then, within our onMount(), we’ll start the TomTom map itself and assign it to the map variable. Plus, we set the container to hold the map on the user interface (UI) as mapElement.

We use longitude, latitude, and zoom variables similarly. The center variable holds the default coordinates the map shows the user once the page loads.

1onMount(() => {
2      map ={
3        key: "<Your API Key",
4        container: mapElement,
5        stylesVisibility: {
6          trafficIncidents: true,
7          trafficFlow: true
8        },
9        center: [longitude, latitude],
10        zoom: zoom
11      });
12    });

We will eventually display these elements on the UI. The div that holds the map displayed on the UI binds directly to the mapElement that we declared and assigned earlier within the onMount.

There’s also a pair of <input/> tags for each of the Start Location and Destination sections, with the four input tags bound to the variables. Then, there’s one extra <input/> tag we similarly use for the zoom variable.

We call this two-way data binding within Svelte. It enables a user to share data in two directions within the application. Our app shares data directly from the UI templates to business logic and vice versa.

This data binding makes automatic data synchronization between the user-controlled interface and logic happen seamlessly. Data binding can simultaneously handle setting the element value and listening to the element change events in our project. This method is what makes Svelte reactive.

Now, back to our project. In the code below, we declare the variables within the logic, and when the value of the input elements changes, it immediately syncs up with the variables.

This method makes data sharing within our component straightforward.

2  <div class="map" bind:this={mapElement}></div>
3  <div>
4   <h3>Start Location</h3>
5   <input placeholder="latitude" bind:value={startLatitude}/>
6   <input placeholder="latitude" bind:value={startLongitude}/>
7  </div>
8  <div>
9   <h3>Destination</h3>
10   <input placeholder="latitude" bind:value={destinationLatitude}/>
11   <input placeholder="latitude" bind:value={destinationLongitude}/>
12  </div>
13  <input placeholder="Zoom number" type="number" bind:value={zoom}/>
14  <button on:click={showRouteLayer}> See route</button>

We then add a button that triggers a showRouteLayer function when the user clicks it. This function takes the inputs the user adds, draws a line between the two locations, and zooms into these newly-selected locations:

1const showRouteLayer = () => {
2  map.addLayer({
3    id: "123",
4    type: "line",
5    source: {
6      type: "geojson",
7      data: {
8        type: "FeatureCollection",
9        features: [
10          {
11            type: "Feature",
12            geometry: {
13              type: "LineString",
14              properties: {},
15              coordinates: [
16                [parseFloat(startLatitude), parseFloat(startLongitude)],
17                [parseFloat(destinationLatitude), parseFloat(destinationLongitude)]
18              ]
19            }
20          }
21        ]
22      }
23    },
24    layout: {
25      "line-cap": "round",
26      "line-join": "round"
27    },
28    paint: {
29      "line-color": "#ff0000",
30      "line-width": 2
31    }
32  });
33  map.setCenter([parseFloat(startLatitude), parseFloat(startLongitude)]);
34  map.setZoom(zoom);

Here, we use TomTom’s out-of-the-box addLayer method to receive the coordinates we’ve set earlier. It then draws a line between the two coordinates.

We also set the line width and color. Then, the UI centers the map on the startLatitude and startLongitude coordinates and zooms in. This centering and zooming in help create a smooth user experience.

Next Steps

Congratulations, you’ve successfully built your first Svelte app with integrated TomTom maps! Adding a map to your application might initially seem tricky and advanced, but using TomTom maps simplifies the entire process. TomTom enables your users to have a smooth, location-targeted experience within your applications.

TomTom helps your users better visualize and interact with the maps. TomTom maps use a user's current coordinates to determine where they are. Plus, users can add their destination's coordinates to have us can calculate the distance and navigation route to get to their destination.

Explore the TomTom documentation and check out all the mapping features you can build with it: heatmaps, animations, traffic flow, search, and so much more. The developer portal offers several code examples to get you started.

Visit the developer portal, register for free, and grab your API key to get started building your map-powered app today.

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.