Build Different

Creating and Using TomTom Geofences with React

Developer Portal
Feb 2, 2022 • Last edit on Jun 21, 20222 min read
Two laptop screens showing React and the TomTom Geofencing API

A geofence is a virtual perimeter (fence) defined around a specific geographic location. We can work with the fence to carry out various operations when an object with internet connectivity — like a mobile phone or car — enters or leaves such an area. For example, we can notify customers when a delivery driver is near their home, match a user with the nearest rideshare driver, or send customers to the closest store location.

In this tutorial, we’ll explore how to set up and work with a geofence in a React application, using the TomTom Maps SDK for Web and the Geofencing API, and how to set up geofences with irregular shapes using the Geofence Creator. Our app will create a circular geofence around where a user clicks on a map. You can find the complete code and see it in action on CodeSandbox.

Prerequisites

To follow this tutorial, you'll need the following:

• Node.js installed on your computer to create a React app. Don’t have Node.js installed? Download the most recent version. • An API key to access TomTom services. If you haven’t yet, you can sign up for a free developer account to get one. • A free Postman account. • Practical knowledge of React, functional components, and Hooks.

Setting Up

First, create a new React app and install the libraries that’ll be used in the demo. Create a new React app with this command:

npx create-react-app <app-name>

The command creates a new folder with the essential React packages on your computer.

Navigate into the project’s directory and install the TomTom Maps SDK for Web and the Turf.js library:

cd <app-name>
npm install @tomtom-international/web-sdk-maps @turf/turf

In this tutorial, we’ll be using the HTTP client library Axios to make HTTP requests. So, install the library with the command:

npm install axios

Now that React and the essential libraries have been installed, we're set to build our application.

Displaying the Map

It’s time to build the app’s user interface (UI) to display a TomTom map. We won’t create any new files to create the UI, as the project bootstrapped by the create-react-app command already includes CSS and JavaScript files. We’ll use these to build out the app.

Open App.js and populate it with the code:

1//App.js
2import { useEffect, useState, useRef } from "react";
3import axios from "axios";
4import "./App.css";
5// TomTom SDK
6import * as tt from "@tomtom-international/web-sdk-maps";
7// styles
8import "@tomtom-international/web-sdk-maps/dist/maps.css";
9
10function App() {
11 const [map, setMap] = useState();
12 const mapContainer = useRef();
13 const AMSTERDAM = { lon: 4.896029, lat: 52.371807 };
14
15
16 useEffect(() => {
17 let map = tt.map({
18 key: <Your_API_Key>,
19 container: mapContainer.current.id,
20 center: AMSTERDAM,
21 zoom: 10,
22 language: "en-GB",
23 });
24 map.addControl(new tt.FullscreenControl());
25 map.addControl(new tt.NavigationControl());
26
27
28 setMap(map);
29 return () => {
30 map.remove();
31 };
32 //eslint-disable-next-line
33 }, []);
34
35
36 return (
37 <div className="container">
38 <nav className="nav">
39 <h1> Geofencing in React</h1>
40 </nav>
41 <div ref={mapContainer} className="map" id="map" />
42 </div>
43 );
44}
45export default App;

We start by importing the TomTom Maps SDK for Web, React hooks, and the Axios and Turf libraries at the top of the file.

Below the imports, the function App is defined. This is the component where our application will live.

In the function App, the useState and useRef hooks create variables that store the map and reference’s the HTML element the map is to be embedded in.

Next, the useEffect hook initiates the map on page load by calling the tt.map constructor with the necessary configurations. These configurations include the container parameter that takes the ID of the DOM element the map is to be embedded in, and the center parameter to center the map on Amsterdam, Netherlands, using its longitude and latitude coordinates.

Finally, the code returns the HTML for the browser to display.

Remember to replace the <Your_API_Key> placeholder with your API key from your TomTom developer account.

Now, paste the CSS styles below into App.css to make the app look nicer than unstyled HTML:

1/*App.css*/
2* {
3 padding: 0;
4 margin: 0;
5 box-sizing: border-box;
6}
7.container {
8 width: 100vw;
9 height: 100vh;
10 display: flex;
11 flex-direction: column;
12 justify-content: space-around;
13 align-items: center;
14}
15.nav {
16 display: flex;
17 justify-content: space-around;
18 align-items: center;
19 width: 100%;
20 height: 10%;
21 background-color: #4169e1;
22 color: #ffffff;
23}
24.nav h1 {
25 padding: 0.3125rem 0;
26 margin-right: 1rem;
27 font-size: 1.25rem;
28 white-space: nowrap;
29}
30.map {
31 width: 100%;
32 height: 90%;
33}

Now, the app can be run locally by navigating into its directory and running the command:

npm start

This command launches the application and opens it in a browser. The result should look like the image below:

image1

Enabling Geofencing

With the map displaying correctly, we can start creating geofences in our app using the TomTom Geofencing API. The Geofencing API enables us to create and manage geofences around specified geographical locations.

Before using the Geofencing API, you need to register an admin key. It provides an extra layer of security to authenticate your requests to the service.

Using Postman, send a POST request to https://api.tomtom.com/location/1/register?&key=Your_API_Key with a body of:

1{
2“secret”: "your_secret",
3}

The body of the request contains a single property: secret. You’ll need this password to configure your account in the future, like registering a new admin key if the former is compromised. So, use a secret you can remember and ensure you don't lose it.

A successful response will generate and log your admin key to the console:

1{
2adminKey: your_admin_key
3}

Creating a Project

Now that we have an admin key, we need to create a Project. This is a collection that stores and manages the geofences we create, each project identified with a unique ID. A geofence must be added to at least one project (it can be added to more) so you need to create a project before creating a geofence.

To create a project, send a POST request to the endpoint:

https://api.tomtom.com/geofencing/1/projects/project?adminKey<ADMIN_KEY>=&key=<API_KEY>

Set the project’s name as a parameter in the request body:

1{
2 "name": "Project_Name"
3}

The API will respond with the project name and ID.

image3

Visit Creating a Project to check out the request on Postman if you want to try it out.

With the project created, we can create geofences around areas of interest.

Creating a Geofence

Let’s explore two different ways we can create geofences: using the Geofencing API, and using the Geofence Creator.

Geofencing API

Until now, Postman has been used to handle all requests to the Geofencing API. Now, we’ll use JavaScript to add an onclick event handler to our TomTom map so that whenever a user clicks on the map, a circular geofence is created centered at the point where the user clicked. event handler to our TomTom map so that whenever a user clicks on the map, the handler creates a circular geofence centered at the point where the user clicked.

First, we define the function createGeofence to create the geofence:

1 async function createGeofence(lng, lat) {
2 const request = await axios({
3 method: "post",
4 url: `https://api.tomtom.com/geofencing/1/projects/<YOUR_Project_ID>/fence?adminKey=<YOUR_ADMIN_KEY>&key=<YOUR_API_KEY>`,
5 headers: {
6 "Content-Type": "application/json",
7 },
8 data: JSON.stringify({
9 name: `Area ${Math.floor(Math.random() * 10000)}`,
10 type: "Feature",
11 geometry: {
12 radius: 200,
13 type: "Point",
14 shapeType: "Circle",
15 coordinates: [lng, lat],
16 },
17 }),
18 });
19 const response = await request.data;
20 return response.id;
21 }

The function above contains the details needed to create a fence around a location. The coordinates parameter takes the latitude and longitude of the site to be geofenced. Then, the parameter passes these coordinates to the function as the lng and lat arguments. shapeType defines the fence’s shape (a circle, in this case), and the radius parameter sets how wide the geofence should span in meters.

A post request is then made to the Geofencing API using Axios. The API creates the geofence and returns an ID.

Next, we add an on-click handler within the useEffect hook that initializes the map on page load.

1map.on("click", (e) => {
2 const { lng, lat } = e.lngLat;
3
4 // creating source data with turf.js
5 const sourceID = `circleData ${Math.floor(Math.random() * 10000)}`;
6 let center = turf.point([lng, lat]);
7 let radius = 10;
8 let options = {
9 steps: 15,
10 units: "kilometers", // or "mile"
11 };
12 let circle = turf.circle(center, radius, options);
13 map.addSource(sourceID, {
14 type: "geojson",
15 data: circle,
16 });
17
18
19 //fetching and drawing the map
20 Promise.all([createGeofence(lng, lat)]).then((result) => {
21 axios({
22 method: "get",
23 url: `https://api.tomtom.com/geofencing/1/fences/${result[0]}?key=<YOUR_API_KEY>`,
24 headers: {
25 "Content-Type": "application/json",
26 },
27 })
28 .then((response) => response.data)
29 .then((result) => {
30 map.addLayer({
31 id: `circle ${Math.floor(Math.random() * 10000)}`,
32 type: "fill",
33 source: sourceID,
34 paint: {
35 "fill-color": "blue",
36 "fill-opacity": 0.6,
37 },
38 });
39 });
40 });

The code above adds an on-click handler to the map. Then, we tap into the event object to get the lnglat property. On a TomTom map, the event object has the lnglat property — the geographical coordinates of the point where the user clicks.

Next, we use the turf.js library, which is the easiest way to display a circle on a TomTom map, to create a GeoJSON circle and add it to the map as a styling source.

Finally, the createGeofence function is called to create the geofence, passing in the lnglat property from the event object as its lat and lng arguments.

The function returns a promise and the geofence ID. We’ll tap into this promise, fetch the details of the newly-created geofence, then display it on the map.

Now, whenever the user clicks on the map, a circular geofence is created that’s centered on the point where the user clicked.

image2

Geofence Creator

To enable developers to easily create complex-shaped geofence in their applications, TomTom introduced the Geofences Creator. It’s a graphical user interface to easily create and edit geofences using the Geofencing API.

Let’s see how seamless the process of setting up a geofence can be using the Geofence Creator. We’ll create a fence around Amsterdam’s most visited nature park — Amsterdam Bos which has a geometry of an irregular polygon.

To launch the Geofence Creator, visit the developer portal and provide your API key and admin key. Visit the Project to store the geofences you want to create. Setting up a fence with Geofence Creator can be done following the steps: 1.. Move the map where you want to put the fence. In this case, Amstelveen, Netherlands.

  1. Click on any of the icons at the top right corner. These represent the shape of the geofence you want to create. You can select a circle, rectangle, polygon, or even search for the location by clicking on the location icon and having the geofence drawn around its geometry. For this tutorial, click on the polygon icon.
  2. A polygon is made up of vertexes. Click on the map to select the first vertex. Then, click on another point to mark the second vertex. Keep clicking to draw out the desired shape.
  3. When you’re done, double-click to end the drawing.
  4. A popup opens, where you can provide a name for the fence and, optionally, any additional properties. The newly created fence is now stored at the Geofencing API service.

Picture1

We’ve created a geofence in the Geofence Creator, but how do we get it to display on our applications? We reference a geofence using its ID.

Below is the code snippet to display a geofence in your applications using its ID:

1map.on("load", () => {
2fetch(
3"https://api.tomtom.com/geofencing/1/fences/<Fence_ID>?key=<Your_API_KEY>"
4)
5.then((response) => response.json())
6.then((result) => {
7console.log(result);
8map.addLayer({
9id: "Fence ",
10type: "fill",
11source: {
12type: "geojson",
13data: result,
14},
15paint: {
16"fill-color": "purple",
17"fill-opacity": 0.6,
18},
19});
20});
21});

In the Geofence Creator, right-click on the created geofence. This opens up a popup containing details about the fence like its name, ID, and any additional properties.

Copy the fence’s ID and replace the <Fence_ID> placeholder in the code snippet above with it. Now the fence should be displayed properly, like in the image below.

Wasn't that seamless? The Geofence Creator makes it simple to set up irregularly shaped geofences.

Sending Notifications When Geofence Transitions Occur

TomTom’s Geofencing API provides an alert service to notify our app when objects with internet connectivity enter or leave a geofenced area. The service can send the notifications to a list of email addresses subscribed to the service or a collection of webhooks, such as a Slack or Microsoft Teams channel.

When the service is enabled, TomTom notifies the email address and webhook URLs whenever an object crosses the fence. Check out this article, Leverage Routing, Geofencing, and Notifications APIs to Send ETA Alerts, for a more in-depth geofencing guide.

Building out the feature enabling notifications on geofence transitions is not within this article’s scope. However, we can add the type of response that TomTom sends about a geofence crossing as stale data to our application’s state to simulate what our application would do with this data after a geofence crossing.

The data received through email after a successful geofencing crossing comes in the following format:

image6

Let’s break down the information in this message. "my_driver" is the object that triggers transition alerts upon entering or leaving the geofence (set by the object service in the Geofencing API). "my_fence" is the name of the geofence the object transitioned through, and 2021-02-10 at 00:52:49 is the time the transition occurred, expressed in the ISO 8601 date format.

We can add an object containing this information attached as properties, to our application’s state, like so:

1const [geofenceData] = useState({
2 object: "my_driver",
3 fenceName: "my_fence",
4 time: new Date().toISOString(),
5 });

Next, we can define a function to simulate geofencing transition alerts in our app using the geofenceData object as a source of mock data.

1function addMarker(lnglat) {
2 const marker = new tt.Marker({ draggable: true })
3 .setLngLat(lnglat)
4 .addTo(map);
5
6 function onDragEnd() {
7 var lngLat = marker.getLngLat();
8 new tt.Popup({ closeOnClick: false })
9 .setLngLat(lngLat)
10 .setHTML(
11 `<div>
12 <p> The object "${geofenceData.object}" crossed "${geofenceData.fenceName}" at ${geofenceData.time}</p>
13 </div>`
14 )
15 .addTo(map);
16
17marker.on("dragend", onDragEnd);
18
19 }

The addMarker function creates a draggable marker centered on the point a user clicks. When the marker is dragged and dropped, a cancelable popup containing the mock data that we added to the application's state is created at the point where the marker was dropped.

Lastly, we add an on-click handler to the map to call addMarker whenever the map is clicked:

1map.on("click", (e) => {
2 addMarker(e.lngLat);
3 });

With that, we have an application that can create real geofences around geographical locations of interest and mimics geofencing crossing alerts. Try it out on CodeSandbox.

Next Steps

Creating and managing a geofence is just one of the features TomTom’s Geofencing API offer. TomTom’s wide range of services enables you to track a vehicle’s location relative to a fence, get notified when a car crosses a fence, determine how long an object has been within and outside a fence, and so much more.

All Postman requests made using the Geofencing API can be found in this Postman collection. Check out our blog post titled What is Geofencing? to learn more about geofencing.

Visit TomTom’s developer portal and sign up for a free developer account to start integrating our web SDK and the Geofencing API into your applications today.

Happy mapping!

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