Build Different

Adding Advanced TomTom Mapping Features to a Modern Vue + Quasar App

Developer Portal
Mar 17, 2022 • Last edit on Jun 21, 20222 min read
Three laptops displaying a TomTom map, Vue, and Quasar sites

Geolocation-based applications help users find locations, keep track of places, and visualize these locations on a map. TomTom Maps API and SDK have made it easier for developers to build these web applications with various mapping services accessible on different devices.

In this tutorial, we'll build a Quasar application to help users search and track the route to a particular location. We'll use TomTom’s Search API, Routing API, and Matrix Routing Service.

You should be familiar with JavaScript and Vue, but you don’t need Quasar experience to follow this tutorial. Feel free to check out our other article, Adding TomTom Maps to a Vue + Quasar App.

Prerequisites

First, ensure Node is on your local development machine. Check if you have it by running this command in your terminal:

node –v

If you don’t have Node, download it. Also, install the Quasar CLI if you don’t already have it.

You’ll also need a TomTom developer account. You get thousands of free requests daily, even for commercial applications. Just pay as you grow!

Setting Up the Project

We’ll set up the Quasar application. First, create a new Vue project using the Quasar CLI:

quasar create route-tracker

This command creates a prompt for you to add details about the project and the suitable development environment. Once the application is successfully created, the Quasar CLI displays the command to change into the newly-created directory. Run this command to start your application:

quasar dev

The result should look like this:

image1

Next, we set up TomTom in our application by installing the required Map SDKs and APIs. So, we’ll install TomTom’s services:

npm install @tomtom-international/web-sdk-maps @tomtom-international/web-sdk-services

Then, install the Maps SDK:

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

You will need to use your TomTom API key in this project. Here's a simple guide to create one for free — no credit card required.

Creating the Layout

The application layout includes a search bar to search for places, a map container to display the map, and the results, which display the calculated distance and time respectively. This image demonstrates the UI layout:

image3

Add this code to the template section of the MainLayout file:

1<q-layout view="lHh Lpr lFf">
2 <q-header elevated>
3 <q-toolbar class="bg-deep-purple-8 text-white">
4 <q-toolbar-title >
5 Route Tracker
6 </q-toolbar-title>
7 </q-toolbar>
8 </q-header>
9 <q-page-container>
10 <!-- To handle the search for location -->
11 <div class="q-pa-md" >
12 <q-form class="q-gutter-md" >
13 <q-input filled v-model="locationQuery" label="Search for an address/location"/>
14 <div>
15 <q-btn label="Search" type="submit" color="deep-purple-8"/>
16 </div>
17 </q-form>
18 <div>
19 <!-- To display the result-->
20 <p>Destination - {{routeAddress}} </p>
21 <p> Estimated Route Distance(KM) - {{destinationDistance}}
22 <br>
23 Estimated Time(MINS) - {{timeToDestination}}
24 </p>
25 <p>
26 {{errorMessage}}
27 </p>
28 </div>
29 </div>
30 </q-page-container>
31 </q-layout>

This code creates the application’s user interface (UI) layout.

Displaying a Map

TomTom Maps APIs enable us to display maps in the application. We can also style our maps to our liking.

Index.template.html, include the CSS stylesheet to handle the maps:

<link rel='stylesheet' type='text/css' href='https://api.tomtom.com/maps-sdk-for-web/cdn/6.x/6.13.0/maps/maps.css'>

Also, import the tt object the index.template.html in the Quasar application. This object represents the object library to access everything related to TomTom maps and services.

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

We create a mapDisplay.vue file in the components folder to handle this section. This component will display the map in our application. Then, we add the map container layout to the mapDisplay.vue file:

1<template>
2 <div id='map' class='window-height'></div>
3</template>

Next, we create a function to display the map and add it to the mapDisplay.vue file:

1displayMap(){
2 const map = tt.map({
3 key: "8h504Wc4AXL6OPndqhrtKf70AovVBL3V",
4 container:'map', // Container ID
5 style: 'tomtom://vector/1/basic-main', //the specified map style
6 });
7 map.addControl(new tt.FullscreenControl());
8 map.addControl(new tt.NavigationControl());
9 const location = [this.longitude,this.latitude];
10 const popupOffset = 25;
11 const marker = new tt.Marker().setLngLat(location).addTo(map);
12 const popup = new tt.Popup({ offset: popupOffset }).setHTML("Your Destination");
13 marker.setPopup(popup).togglePopup();
14 }

Then, we call the function to display the map in the mapDisplay.vue file using the mounted() lifecycle method:

1mounted() {
2 this.displayMap()
3 }

Integrating the Search API

TomTom's Search API performs various functions such as fuzzy search, autocomplete, geocoding, and reverse geocoding.

Fuzzy Search

We’ll mainly focus on the fuzzy search, which searches for addresses and places like hospitals, bars, and restaurants. We can also restrict the search to a particular region or geometry.

The query’s result gives a detailed description of the location that matches the specific query text partially.

To implement fuzzy search, start by importing the tt object from the SDK in MainLayout.vue:

import tt from "@tomtom-international/web-sdk-services";

Then, in MainLayout.vue, create the form to handle the search:

1<div class="q-pa-md" >
2 <q-form @submit="SearchAndCalculateRoute()" class="q-gutter-md" >
3 <q-input filled v-model="locationQuery" label="Search for an address/location"/>
4 <div>
5 <q-btn label="Search" type="submit" color="deep-purple-8"/>
6 </div>
7 </q-form>

Next, create a function to handle the search:

1const _this = this
2 // Using the fuzzySearch service
3 await tt.services.fuzzySearch({
4 key: 'INSERT API KEY HERE',
5 query: this.locationQuery //The input gotten from the search
6 }).then(function (response) {
7 _this.routeAddress = response.results[0].address.freeformAddress
8 _this.routeLatitude = response.results[0].position.lat
9 _this.routeLongitude = response.results[0].position.lng
10 })

This code performs the search function and displays the address’s first result while storing the latitude and longitude to use in the other services.

We can also add the bounding box parameter to refine the search. The bounding box is a limited area within the search results, and without it, the search considers the whole world. This parameter accepts longitude and latitude values of the place to search.

<!-- Display the result of the search -->
<p> Destination - {{routeAddress}} </p>

Point of Interest Search

Another feature that we’ll add to our map is the ability to find specific places around the location searched for. We do this using Points of Interest Search, a service provided by TomTom that enables us to find a specific type of place, like restaurants, arts centers, or even transit stations.

We’ll implement this in the mapDisplay.vue file to display the places on the map. As an example, we’ll search for nearby gas stations. To implement fuzzy search, start by importing the tt object from the SDK in MainLayout.vue. The tts object is imported in the mapDisplay.vue:

import tts from "@tomtom-international/web-sdk-services";

Then, a function is created to call the service when the map has been rendered on the page:

1tts.services.poiSearch({
2 key: 'INSERT API KEY HERE'
3 query: Gas Stations,
4 center: [ _this.latitude, _this.longitude ]
5 })
6 .then(function(data) {
7 _this.stations = data.results})
8 .catch((err) => {
9 console.log(err)
10 });

The service requires an API key, a query that represents the place to find, and a center location. These parameters are required for its function. The center location is based on the position gotten from the fuzzy search we did earlier. With this, we’re able to find the various gas stations at the location we searched for.

Next, we use the result of the gas stations found and display them respectively on our map.

1// looping through the result to get the value of each location
2 this.stations.forEach(function (e) {
3 const popupOffset = 25;
4 // assisgn the markers to a location the map
5 const marker = new tt.Marker().setLngLat(e.position).addTo(map);
6 // set the popup to display the respective addresses of the position.
7 const popup = new tt.Popup({ offset: popupOffset }).setHTML(
8 "<p>" + e.poi.name + "<br>" + e.address.freeformAddress + "</p>" );
9 marker.togglePopup(popup).setPopup(popup);
10 });

With the above code, we’re able to loop through each result obtained from the search and display the various markers on the map. It looks something like this:

image2

Integrating the Routing API

TomTom Routing API offers various services such as the Matrix Routing Service. This service calculates a matrix of route summaries for a set of routes defined with origin and destination locations. It calculates travel time and total distance traveled for each route.

For this tutorial, we’ll use Matrix Routing to find a route from the user’s location to the place they found in their search.

We’ll first use the Geolocation Web API to request access to the user’s current location, so add this code to MainLayout.vue:

1created(){
2 navigator.geolocation.getCurrentPosition(
3 position => {
4 this.lat = position.coords.latitude;
5 this.lng = position.coords.longitude;
6 },
7 error => {
8 console.log(error.message);
9 }
10 );
11},

Now when the application loads, the app requests access to the current location so we can calculate the route later.

Next, we calculate the route using the Matrix Routing Service:

1// Using the matrix routing
2 const origins = [{ point: { latitude: this.userLat, longitude: this.userLng } }] //The location of the user as starting point
3 const destinations = [{ point: { latitude: this.routeLatitude, longitude: this.routeLongitude} }] // The location of the destination as final point
4
5 await tt.services.matrixRouting({
6 key: 'INSERT API KEY HERE',
7 origins: origins,
8 destinations: destinations,
9 traffic: true, // specifying the traffic data
10 travelMode: 'car' //Specifying a routing parameter
11 }).then(function(routeData){
12 _this.timeToDestination = (routeData.matrix[0][0].response.routeSummary.travelTimeInSeconds / 60).toFixed(2)
13 _this.destinationDistance = (routeData.matrix[0][0].response.routeSummary.lengthInMeters / 1000).toFixed(2)
14
15
16
17 })
18 .catch((err) => {
19 console.log(err)
20 _this.errorMessage = 'Locations cannot be mapped. Try another location'
21 });
22 }

The function uses the start location and stop location, stored in strings.

The application stores and displays the result of the calculated distance and time:

1<p> Estimated Route Distance(KM) - {{destinationDistance}}
2 <br>
3 Estimated Time(MINS) - {{timeToDestination}}
4 </p>

We can also specify common routing parameters to restrict the calculated path. Some parameters are optional, while others are required, such as:

  • routeType specifies the type of optimization used when calculating routes. It can be fastest, shortest, thrilling, and so on.
  • traffic value can be true or false.
  • travelMode specifies the mode of travel, such as a truck, taxi, bus, or van.
  • vehicleMaxSpeed sets the expected speed in kilometers per hour. The value ranges from 0 to 250.

This animation shows the application in action:

image

You can find this application’s complete code in its GitHub repo.

Next Steps

In this tutorial, we enhanced a Quasar application with a TomTom map to help users search for and calculate a route's distance. TomTom’s SDK made adding these advanced mapping functions quick and seamless.

You can add even more functions to this mapping application or create a unique application. Explore the developer portal documentation to learn how to use TomTom's various tools and start using TomTom Maps today by signing up to access your free API key.

Get the developer
newsletter.

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

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