Build Different

Creating and Using TomTom Geofences with Vue

Developer Portal
Feb 19, 2022 • Last edit on Feb 22, 20222 min read

Geofences are virtual fences around a given geographical area. They enable us to monitor a site and add functionality to a map. We can determine if an object is inside or outside the area using its coordinates. A geofencing API’s reporting service can even provide the distance between the object and the geofence.

Geofences help solve many practical problems, including enabling ride-hailing apps, notifying a customer when their parcel or delivery is almost at their doorstep, detecting deviation from the route or potential theft of trucks carrying valuable cargo, and much more. So, in this tutorial, let’s explore how to add a geofence to a TomTom map within a Vue application. We’ll then use our geofence to track movement into and out of an area on the map. Our Vue application will run on Vite.

You should be familiar with JavaScript and Vue to follow this tutorial. We’ll show you how to work with TomTom’s features. You also need a TomTom developer account to follow along — it’s free even for commercial use with thousands of daily requests (then you can pay as you grow if you need more capacity, or reach out to TomTom for a personalized offer).

Getting Started

Installing Vite

Vite provides us with a fast development server. To get started with Vite, run the following command:

npm init vite@latest geofence -- --template vue

You can then install other external npm libraries that you might need for your project.

For a deep dive into everything you need to know about getting started, check out Vite’s complete documentation.

Installing TomTom Maps SDK

Next, we install TomTom Maps SDK to view the map on the Document Object Model (DOM) by running this command:

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

Installing Axios

Then, we install Axios to handle API requests:

npm i axios

Adding a Map

Now, let’s add our map into our Vue component. First, let’s import all the necessary libraries inside our <script> tag, starting with Axios:

import axios from 'axios';

We also import onMounted, ref, and reactive into our component. We’ll use this inside our Vue composition API:

import { onMounted, ref, reactive } from 'vue';

We’ll then add the setup() method to the component to initialize and insert the map:

1export default {
2 name: 'App',
3 setup() {
4 const mapRef = ref(null);
5 onMounted(() => {
6 const tt = window.tt;
7 var map = tt.map({
8 key: '<YOUR API KEY HERE>',
9 container: mapRef.value,
10 style: 'tomtom://vector/1/basic-main',
11 });
12 map.addControl(new tt.FullscreenControl());
13 map.addControl(new tt.NavigationControl());
14 })
15
16 return {
17 mapRef,
18 };
19 }
20}

Inside the setup() method, we used the ref function to create a variable called mapRef. Refs allow us to access the DOM element, which is how we add the map.

Next, we use our onMounted life-cycle to initialize and add the map to the DOM while the component is mounted. We set mapRef as the map’s container and add visual controls for navigation and full-screen to the map using map.addControl. In the end, we’ll return mapRef and use it in our <template>.

We use ref to add the map to the <div> element.

<div id="map" ref="mapRef"></div>

Let’s also add these styles:

1<style>
2#app {
3 font-family: Avenir, Helvetica, Arial, sans-serif;
4 -webkit-font-smoothing: antialiased;
5 -moz-osx-font-smoothing: grayscale;
6 text-align: center;
7 color: #2c3e50;
8 margin-top: 60px;
9}
10#map {
11 height: 60vh;
12}
13</style>

Creating the Geofence

Our next step is to create the geofence. The geofencing service enables us to draw a virtual boundary, and we can use the Geofences creator tool to draw geofences of any shape or form. Applications can then use this virtual boundary to check if a location or object is inside or outside the enclosed space. A particular object’s coordinates — its latitude and longitude — allow us to check if it's within the geofence.

To get these coordinates and determine the object’s location, we want a user to click on the map and have the app automatically draw a circular geofence centered on that point.

We need an Admin Key to do this. The Admin Key is one of the query parameters we need to handle the geofence’s API requests. Then, we’ll use Postman to send a POST request to TomTom’s API to register our Admin Key.

This request will include a body containing a secret phase. We’re using "my_secret_key” for this project. However, you can use another custom string.

1{
2 "secret": "my_secret_key"
3}

We’re also using our API key as a parameter, so it’s all tied to one account:

https://api.tomtom.com/geofencing/1/register?key=Your_API_Key

image1

We’ll get back a response containing our adminKey.

Creating a New Project

We now have the adminKey, but we need to create a project that connects to the geofence we’re about to draw. Every geofence is associated with a particular project.

Send another POST request to register the new project:

https://api.tomtom.com/geofencing/1/projects/project?key=${apiKey}&adminKey=${adminKey}

Send it with the project name as the body:

1{
2 "name": "Geofence map"
3}

image3

The response contains the project id and name.

Creating the Geofence

Now that we have our project, we can create the geofence in our code using its coordinates. First, let’s install Turf to help us draw on the map.

npm i @turf/turf

Go back inside the onMounted component and add map.on to monitor where and when the user clicks. The app will use that particular coordinate to draw our geofence. Send the request like this:

1map.on('click', function (event) {
2const position = event.lngLat;
3 console.log(position);
4axios.post('https://api.tomtom.com/geofencing/1/projects/${YOUR_PRODUCT_ID}/fence?key=${YOUR_API_KEY}=${YOUR_ADMIN_KEY}',
5 {
6 name: `Our location ${Math.floor(Math.random() * 10000)}`,
7 type: 'Feature',
8 geometry: {
9 radius: 85,
10 type: 'Point',
11 shapeType: 'Circle',
12 coordinates: [position.lat, position.lng],
13 },
14 }
15 )
16}

We get back a response containing information about the geofence we just created. In the response, we use turf to collect our coordinates and eventually feed them into map.addSource.

1.then((res) => {
2 console.log(res.data);
3 console.log(position)
4 let _center = turf.point([position.lng,position.lat]);
5 let _radius = 45;
6 let _options = {
7 steps: 80,
8 units: 'kilometers' // or "mile"
9 };
10
11 let _circle = turf.circle(_center, _radius, _options);
12
13 map.addSource("circleData", {
14 type: "geojson",
15 data: _circle,
16 });
17
18 map.addLayer({
19 id: "circle-fill",
20 type: "fill",
21 source: "circleData",
22 paint: {
23 "fill-color": "red",
24 "fill-opacity": 0.5,
25 },
26 });
27 //map.setCenter([parseFloat(position.lat), parseFloat(position.lng)]);
28 })
29 .catch((err) => console.log(err));

map.addLayer collects the data through map.addSource and uses it to draw the geofence directly on our map.

image2

When we click any point on the map, the app takes the coordinates, creates a new geofence, and uses addLayer to draw a circular outline.

Here’s the full code inside onMounted:

1 onMounted(() => {
2 const tt = window.tt;
3 var map = tt.map({
4 key: '{YOUR_API_KEY}',
5 container: mapRef.value,
6 style: 'tomtom://vector/1/basic-main',
7 zoom: 5,
8 center: [12.3, 32.992578],
9 });
10 map.addControl(new tt.FullscreenControl());
11 map.addControl(new tt.NavigationControl());
12 state.map = map;
13
14 map.on('click', function (event) {
15 const position = event.lngLat;
16 console.log(position);
17 axios
18 .post(
19 'https://api.tomtom.com/geofencing/1/projects/1c2f4c1d-c1eb-43b3-a023-18e503469104/fence?key=${YOUR_API_KEY}=${YOUR_ADMIN_KEY}',
20 {
21 name: `Our location ${Math.floor(Math.random() * 10000)}`,
22 type: 'Feature',
23 geometry: {
24 radius: 85,
25 type: 'Point',
26 shapeType: 'Circle',
27 coordinates: [position.lat, position.lng],
28 },
29 }
30 )
31 .then((res) => {
32 console.log(res.data);
33 console.log(position)
34 let _center = turf.point([position.lng,position.lat]);
35 let _radius = 45;
36 let _options = {
37 steps: 80,
38 units: 'kilometers' // or "mile"
39 };
40 let _circle = turf.circle(_center, _radius, _options);
41 map.addSource("circleData", {
42 type: "geojson",
43 data: _circle,
44 });
45 map.addLayer({
46 id: "circle-fill",
47 type: "fill",
48 source: "circleData",
49 paint: {
50 "fill-color": "red",
51 "fill-opacity": 0.5,
52 },
53 });
54 //map.setCenter([parseFloat(position.lat), parseFloat(position.lng)]);
55 })
56 .catch((err) => console.log(err));
57 });
58 });

Handling Geofence Notifications

TomTom maps enable us to monitor our geofence, checking if an object is within or outside it. This feature is mostly beyond the scope of this tutorial. You would need to register and track an object and connect your backend to the Notifications API and Geofencing Alert Service. This approach would require a webhook and email where it will send notifications if the device crosses the geofence.

Instead, using its coordinates, we can use the TomTom Geofencing Report service to determine if an object is within or outside the geofence. Let’s first create an object’s location and add a marker for that location on the map. We make a new function directly under our onMounted component called addMarker.

1 function addMarker(map) {
2 const tt = window.tt;
3 var location = [-12.3423, 65.67346189482023];
4 var popupOffset = 25;
5
6 var marker = new tt.Marker().setLngLat(location).addTo(map);
7 var popup = new tt.Popup({ offset: popupOffset }).setHTML("Your object!");
8 marker.setPopup(popup).togglePopup();
9}

Then add this code to our onMounted component:

1onMounted(() => {
2 // [...]
3 addMarker(map);
4})

This marker will display on our map, like this screenshot:

image4

We can now take our object’s coordinates and send a POST request using this endpoint. We’ll use the projectId, apiKey, adminKey, and the object’s latitude and longitude as query parameters:

https://api.tomtom.com/geofencing/1/report/${projectId}?key=${apiKey}&adminKey=${adminKey}&point=${lat,lng}

The response looks like this:

1{
2 "summary": {
3 "project": "c2f56e6d-8395-4aa2-bf64-e36f7b7d229c",
4 "type": "Point",
5 "coordinates": [
6 41.670966,
7 2.750529,
8 0.0
9 ],
10 "range": 0.0
11 },
12 "inside": {
13 "type": "FeatureCollection",
14 "features": },
15 "outside": {
16 "type": "FeatureCollection",
17 "features": [
18 {
19 "id": "0c803717-b862-4548-ab47-20bf544b2d84",
20 "name": "Geofence map",
21 "distance": 3298398.0,
22 "type": "Feature",
23 "geometry": {
24 "type": "Point",
25 "coordinates": [
26 12.138017,
27 6.137388
28 ]
29 },
30 "properties": {
31 "maxSpeedKmh": 70
32 }
33 }
34 ]
35 }
36}

The response shows whether the point is inside or outside the app’s geofences. The response also includes the object’s distance from the geofence.

Conclusion

Congratulations on completing the tutorial! We’ve explored geofences and demonstrated how to use them to optimize mapping and tracking in your Vue application. Here’s a link to our complete code.

You can customize TomTom’s Geofencing API to handle your unique use case, from tracking flower deliveries to notifying ridesharing travelers when their lift to the airport is almost there to alerting fleet managers when their truck packed with computer equipment is not where it should be. Now that you’ve learned how to use TomTom with Vue, dive in and get started adding geofencing features to your next app.

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