Decoded

Using the Snap to Roads API with React

David Atanda
Jun 24, 2022 • Last edit on Jun 24, 20228 min read
Using the Snap to Roads API with React

Using the Snap to Roads API with React

TomTom’s Snap to Roads API uses GPS data to reconstruct driver journeys. The API matches location data with road network information to determine the most probable route.

The Snap to Roads API also takes other factors into account, such as what type of vehicle is being driven, speed limits, lanes, and the amount of time it has previously taken the driver to reach various locations. These factors are sent as parameters by the REST API.

You can also record multiple point coordinates along the driver’s journey. Then, we can take these point coordinates and send them to the API, which takes the coordinates and returns relevant information about the coordinate routes. The API’s response can also include more descriptive details on the road traveled, such as names, types of roads, speed restrictions, class of road, etc.

Snap to Roads allows for smooth visualization of relevant information in ride-hailing services and on-demand delivery applications. It’s also useful for route tracking in fleet logistics and insurance applications. You can use it for information about road attributes, such as speed limit, elevation, and road ownership.

In this article, we’ll build a demo in which we’ll input two location coordinates, send this information to the Snap to Roads API, and draw the returned routes on our TomTom maps. This will provide a helpful visual representation of the new routes and how to use them.

Getting Started

There are many ways to spin up a React application, but it’s advisable to use the Create React App (CRA) library.

Let’s jump straight to the code. To create a React app using Create React App, make sure you currently have Node.js installed. You can check to see if you have Node.js installed by typing the following into your terminal:

node -v

If Node.js is installed, that command should return the current version. If not, go to the Node.js website and download the latest version.

Next, go into the terminal/command prompt and initiate your app using the name.

npx create-react-app snap-to-road

Navigate into your project folder:

cd snap-to-road

You can now start the project:

npm start

You need to be able to send API requests with your endpoints, so you need an API key from TomTom maps. Sign in to TomTom, generate an API key, and edit it to enable the Snap to Roads API:

Photo 1

Installation

Before you can use TomTom in your app, you’ll have to install the TomTom package and axios:

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

Axios will allow us to make API requests to the Snap to Roads API:

npm i axios

Adding the TomTom Map

Now, let’s go into the component where we will create the map:

1import "./styles.css";
2import "@tomtom-international/web-sdk-maps/dist/maps.css";
3import * as ttmaps from "@tomtom-international/web-sdk-maps";
4import { useState, useEffect, useRef } from "react";
5
6export default function App() {
7 const mapElement = useRef();
8 const [mapZoom, setMapZoom] = useState(17);
9 const [map, setMap] = useState({});
10
11 useEffect(() => {
12 let map = ttmaps.map({
13 key: "{{TOMTOM_API_KEY}}",
14 container: mapElement.current,
15 center: [12.3, 32.992578],
16 zoom: mapZoom
17 });
18 setMap(map);
19 return () => map.remove();
20 }, []);
21
22 return (
23 <div className="App">
24 <div ref={mapElement} className="mapDiv"></div>
25 </div>
26 );
27}

This imports the TomTom library and displays it in the DOM using React’s useRef.

Next, import the TomTom library and default CSS styles into App.js. You’ll also import useState and useEffect.

You need to add certain values, like the map zoom value and the map itself using useState. Then, you can initialize the map with useEffect and display it with mapElement.

Photo 2

Using the Snap to Roads API

Now, let’s say we’re moving from point A (4.6104, 52.3757) to point B (4.6140, 52.3834). As we send these coordinates to the API, we also send two parameters: fields and key (our API key). The fields object contains the specific information you need from the API endpoint. For this example, this appears as follows:

1{
2 projectedPoints {
3 type,
4 geometry {
5 type,
6 coordinates
7 },
8 properties {
9 routeIndex
10 }
11 }, route {
12 type,
13 geometry {
14 type,
15 coordinates
16 },
17 properties {
18 id,
19 speedRestrictions {
20 maximumSpeed {
21 value,
22 unit
23 }
24 }
25 }
26 }
27}

You can also find more nested fields sample objects in our documentation.

Let’s get back to the code. Within the component, import axios and create a getSnapFunction that makes a request to the API.

1import axios from "axios"
2
3const getSnapFunction = () => {
4 axios.get("https://api.tomtom.com/snap-to-roads/1/snap-to-roads?points=4.6104,52.3757;4.6140,52.393&fields={projectedPoints{type,geometry{type,coordinates},properties{routeIndex}},route{type,geometry{type,coordinates},properties{id,speedRestrictions{maximumSpeed{value,unit}}}}}&key=8h504Wc4AXL6OPndqhrtKf70AovVBL3V").then((res) =>
5 {
6 console.log(res.data)
7 res.data.route.forEach(
8 (item) => {
9 map.addLayer({
10 id: Math.random().toString(),
11 type: "line",
12 source: {
13 type: "geojson",
14 data: {
15 type: "FeatureCollection",
16 features: [
17 {
18 type: "Feature",
19 geometry: {
20 type: "LineString",
21 properties: {},
22 coordinates: item.geometry.coordinates
23 }
24 }
25 ]
26 }
27 },
28 layout: {
29 "line-cap": "round",
30 "line-join": "round"
31 },
32 paint: {
33 "line-color": "#ff0000",
34 "line-width": 2
35 }
36 });
37 }
38 )
39 map.setCenter([parseFloat(4.6104), parseFloat(52.3757)]);
40 }).catch((err) => console.log(err))
41 }

This returns the reconstructed route. Then, it loops this response through the route array.

Next, we used map.addLayer to draw each property of the array on the map. It now forms the full route, taking you from the takeoff point to the destination.

Finally, map.setCenter enables us to center the map on the route. Here’s the final map:

Photo 3

We’ve just covered the Synchronous Snap to Roads API. However, there’s also an Asynchronous Snap to Roads API, where users make a POST request and get back a batch ID. While making this request, we will send the several coordinate points and the query property within the body.

1axios.post('https://api.tomtom.com/snap-to-roads/batch/1?key={TOMTOM_API_KEY}', {
2 {
3 batchItems: [
4 {
5 query: "/snap-to-roads?fields={projectedPoints{type,geometry{type,coordinates},properties{routeIndex}},route{type,geometry{type,coordinates},properties{id,speedRestrictions{maximumSpeed{value,unit}},address{roadName,roadNumbers,municipality,countryName,countryCode,countrySubdivision},elementType,traveledDistance,privateRoad,partOfTunnel,frc,formOfWay,roadUse,laneInfo{numberOfLanes},heightInfo{height,chainage},trafficSign{signType,chainage},trafficLight}},distances{total,ferry,privateRoad,publicRoad,road,offRoad}}&vehicleType=PassengerCar&measurementSystem=imperial",
6 post: {
7 points: [
8 {
9 type: "Feature",
10 geometry: {
11 type: "Point",
12 coordinates: [
13 19.4389141359581,
14 51.78057462411982
15 ]
16 }
17 },
18 {
19 type: "Feature",
20 geometry: {
21 type: "Point",
22 coordinates: [
23 19.439257458711324,
24 51.78057794294989
25 ]
26 }
27 },
28 {
29 type: "Feature",
30 geometry: {
31 type: "Point",
32 coordinates: [
33 19.43963296797358,
34 51.78064100067553
35 ]
36 }
37 },
38 {
39 type: "Feature",
40 geometry: {
41 type: "Point",
42 coordinates: [
43 19.44012113001449,
44
45
46
47
48
49
50
5151.780690783028064
52 ]
53 }
54 }
55 ]
56 }
57 },
58 {
59 "query": "/snap-to-roads?fields={projectedPoints{type,geometry{type,coordinates},properties{routeIndex}},route{type,geometry{type,coordinates},properties{id,speedRestrictions{maximumSpeed{value,unit}},address{roadName,roadNumbers,municipality,countryName,countryCode,countrySubdivision},elementType,traveledDistance,privateRoad,partOfTunnel,frc,formOfWay,roadUse,laneInfo{numberOfLanes},heightInfo{height,chainage},trafficSign{signType,chainage},trafficLight}},distances{total,ferry,privateRoad,publicRoad,road,offRoad}}&vehicleType=PassengerCar&measurementSystem=metric",
60 post: {
61 points: [
62 {
63 type: "Feature",
64 geometry: {
65 type: "Point",
66 coordinates: [
67 19.4389141359581,
68 51.78057462411982
69 ]
70 }
71 },
72 {
73 type: "Feature",
74 geometry: {
75 type: "Point",
76 coordinates: [
77 19.439257458711324,
78 51.78057794294989
79 ]
80 }
81 },
82 {
83 type: "Feature",
84 geometry: {
85 type: "Point",
86 coordinates: [
87 19.4389141359581,
88 51.78057462411982
89 ]
90 }
91 },
92 {
93 type: "Feature",
94 geometry: {
95 type: "Point",
96 coordinates: [
97 19.439257458711324,
98 51.78057794294989
99 ]
100 }
101 },
102 {
103 type: "Feature",
104 geometry: {
105 type: "Point",
106 coordinates: [
107 19.43963296797358,
108 51.78064100067553
109 ]
110 }
111 },
112 {
113 type: "Feature",
114 geometry: {
115 type: "Point",
116 coordinates: [
117 19.44012113001449,
118 51.780690783028064
119 ]
120 }
121 }
122 ]
123 }
124 }
125 ]
126}
127})

The response will contain a batch ID:

1{
2 "batchId": "16178e70-8331-459f-abc8-251e708f5edb"
3}

We now take this batch ID and send another request to another endpoint, checking the status of our Snap API request:

axios.get('https://api.tomtom.com/snap-to-roads/batch/1/c435cae3-c8f2-4d76-b08b-304529c967eb/status?key={TOMTOM_KEY}').then((res) => console.log(res.data)).catch((err) => console.log(err)

If it’s ready, it will return Completed.

1{
2 "state": "Completed",
3 "statistics": {
4 "totalCount": 2,
5 "successes": 2
6 }
7}

As the processing of batch data may take some time to complete, it is important to check the status before attempting to obtain the route data. Attempting to download route data before processing has completed will result in an error.

Once the process is complete, you can get the route data by sending a GET request to the download endpoint. This sends a response with the route data. The route data will take the shape of the query property in the body of the POST request we sent earlier.

axios.get('https://api.tomtom.com/snap-to-roads/batch/1/c435cae3-c8f2-4d76-b08b-304529c967eb?key={TOMTOM_KEY}').then((res) => console.log(res.data)).catch((err) => console.log(err)

Conclusion

Now that you know how to use TomTom’s Snap to Roads API to retrieve relevant information about a set of route coordinates, and display the route on a map in our React app, you can start using this API in your own applications. For example, you could use this API to create a fleet logistics application that analyzes delivery drivers’ routes and speed. You can use this to determine how fast delivery orders are fulfilled.

Synchronous Snap to Roads is best for analyzing single trips. If you need to analyze batches of trips in one call, try Asynchronous Snap to Roads.

To learn more about each endpoint of this API, explore the following resources:

Visit the TomTom Developer Portal to learn more about TomTom Maps.

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