Build Different

How to Reconstruct a Route from Data Points with the Snap to Roads API

Developer Portal
Jan 5, 2023 • Last edit on Jan 6, 20239 min read
Two mobile devices showing points on a map and a reconstructed route with TomTom Snap to Roads API

If you work in fleet management, you’ll likely encounter situations where you need to map a route using data points or coordinates. Whether you’re trying to reconstruct a trip to verify mileage, determine where a delay occurred, or plan for future optimization, you can use the TomTom Snap to Roads API to draw route information based on the coordinates you feed into it.

The person or system using the API feeds several coordinates for a known route and other optional information such as the heading, timestamp, and vehicle types. After that, it communicates with the TomTom engine, which returns the route information.

In this tutorial, we will recreate part of a highway using coordinates from a GPX trace.

Next, we’ll feed this information to the Snap to Roads API, which will return the highway’s route information. Then, to confirm that the Snap to Roads API returned the correct routes, we’ll use TomTom’s Maps SDK to display the road using the coordinates returned.

Prerequisites

Before getting started, you need to have:

  • An understanding of JavaScript
  • An understanding of the React library. Even though we’ll use React in this tutorial, you can use the insights gained to implement the concept using Angular, Vue, or any other JavaScript framework you prefer.
  • Node.js installed in your system, since we’ll use npm to create the React app and install its dependencies. You may also use Yarn.
  • A TomTom developer API key. If you haven’t yet, sign up for a free TomTom developer account.

Setting up

In your working folder, create a react app called tomtom-snap-to-roads by running the commands below.

npx create-react-app tomtom-snap-to-roads
cd tomtom-snap-to-roads

Then, store your API key in an environment variable to avoid explicitly storing it in your file. You can do that by running the following command:

REACT_APP_API_KEY="<YOUR-API-KEY>" npm start

The app will launch at localhost:3000.

We’ll need the TomTom Map SDK and the Map Web Services dependencies. Install them using:

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

First, we need to add CSS styling to size the map container correctly in the App.css file. This app is found in the React directory (tomtom-snap-to-roads). Open it and add this code:

1.routeMapDemo {
2 height: 100vh;
3}

In the same directory, open the App.js file and clear its contents. This will prevent errors that may arise when trying to modify the code. In the tutorial, we’ll add the code we need in a step-by-step fashion.

Add the following lines to import the required modules:

1import './App.css';
2import '@tomtom-international/web-sdk-maps/dist/maps.css'
3import mapSDK from '@tomtom-international/web-sdk-maps'
4import mapServices from '@tomtom-international/web-sdk-services'
5import { React, useState, useEffect, useRef } from 'react'
6And then add the following skeleton functional component to it.
7function App() {
8 return (
9 <div className="App">
10 <div ref={mapContainer} className="routeMapDemo" />
11 </div>
12 );
13}
14export default App;

Adding the Code to the App Functional Component

Let’s start by adding the constants to store our API key, the map container, zoom level, and the map.

1 const API_KEY = process.env.REACT_APP_API_KEY;
2 const mapContainer = useRef();
3 //use this to change the zoom level of the map
4 const [zoomLevel, setZoomLevel] = useState(3);

Create and initialize a variable for storing the Traffic Flow URL endpoint.

let traffic_flow_url = encodeURI('https://api.tomtom.com/traffic/services/4/flowSegmentData/relative0/12/json?point=38.219901,-85.773140&unit=KMPH&openLr=false&key=' + API_KEY);

We passed a point found on the Kentucky Highway. You can use various methods to get the coordinates of a route, including the Reverse Geocoding API. For simplicity, we added coordinates of a route manually using the coords_arr array. The coordinates can be found here. Note that we start with the longitude and then the latitude, which we will need soon pass into the Snap to Roads API.

But first, we need to retrieve the latitude and longitude and correctly set them to the coordinates that the API needs. To do that, let’s create a function called mainProcessor.

1async function mainProcessor(targetMap) {
2
3 let coords_arr = [//Add the linked coordinates here]
4
5 let coords_length = coords_arr.length
6 let full_coord = ""
7
8 coords_arr.forEach((coordinate, index) => {
9 //whenever a comma is encountered, split the text into an array
10 let points = coordinate.split(",")
11 //accessing the latitude and longitude from the split array
12
13 let latitude = points[0]
14 let longitude = points[1]
15 full_coord = full_coord.concat(longitude + "," + latitude)
16 if (index < (coords_length - 1)) {
17 full_coord = full_coord.concat(";")
18 }
19
20 });
21
22 //fields object
23 let fields = "{projectedPoints{type,geometry{type,coordinates},properties{routeIndex,snapResult}},route{type,geometry{type,coordinates},properties{id,linearReference,speedLimits{value,unit,type},address{roadName,roadNumbers,municipality,countryName,countryCode,countrySubdivision},traveledDistance{value,unit},privateRoad,partOfTunnel,urbanArea,elementType,frc,formOfWay,roadUse,laneInfo{numberOfLanes},heightInfo{height,chainage,unit},trafficSigns{signType,chainage,unit},trafficLight}},distances{total,ferry,road,privateRoad,publicRoad,offRoad,unit}}"
24
25 let snap_to_roads_url = 'https://api.tomtom.com/snap-to-roads/1/snap-to-roads?points=' + full_coord + '&fields='+ fields +'&key=' + API_KEY
26 snap_to_roads(snap_to_roads_url, targetMap)
27 }

The function uses an async await function to load the response and a for-each loop to extract the array’s contents. In the for-each loop, we use an arrow function to append the coordinates to a string and separate them using a semicolon. The if statement prevents the code from appending the semicolon after the last coordinate. The fields object specifies what to include in the API’s response.

We have the snap_to_roads URL, which was retrieved from the API’s documentation page. At the end of the function, we call a function called snap_to_roads, which is used to get the reconstructed routes and draw the map. We’ll add that later. Let’s break a bit and talk about the Snap to Roads API.

A Brief Overview of the Snap to Roads API

When you visit the Snap to Roads API Explorer page, you’ll see these endpoints:

image 1

There are two sections, the Synchronous Snap to Roads API and Asynchronous Snap to Roads API. We’ve already introduced the first one. The second is used for sending snap requests in batches. That is, we can send multiple Snap to Roads API requests at once. The Asynchronous API returns a batch ID in response, which we can use to track a batch’s status or download it using the next two endpoints. We won’t discuss the asynchronous API since this tutorial focuses on the synchronous type.

Synchronous and asynchronous APIs have something in common: Both have the fields parameter in the request body. The engine uses this to know what to include in the response. One notable difference between the asynchronous and synchronous API is that we can pass in the geometry and type of a point in the request body of the asynchronous API.

Let’s focus on the synchronous API, for which we’ll use the GET endpoint. Click the down arrow to explore the parameters you can pass in the endpoint. Try feeding in some coordinates and click the EXECUTE button to see the response. Leave the fields parameter as it is.

You’ll see a response like the one below. This was downloaded and rendered in another program, which accounts for the difference in appearance.

image 2

It returns the route, the point details we fed to the request, their snap results (if matched or not), and the distance.

We’re interested in the route, so let’s check it out.

image 3

It contains all the points in order, capturing their type and geometry. The geometry object includes the shape, meaning the graphical type of the point. The coordinates of the line string are also contained in the geometry object. In a line string, there must be at least two points.

image 4

For the properties, we get information such as the speed limit, road address, lane information, and so on.

image 5

That’s enough theory. Let’s proceed with creating the React app.

Getting the Reconstructed Coordinates and Displaying the Map

Add the snap_to_roads function we introduced in the last snippet.

1 async function snap_to_roads(snapUrl, targetMap) {
2 let snap_response = await fetch(snapUrl);
3 let roads_data = await snap_response.json();
4 let routes_arr = roads_data.route
5
6 //extracting the coordinates for setting the map's boundaries
7 let boundary_coordinates = routes_arr[0].geometry.coordinates
8 routes_arr.forEach((point, index) => {
9 boundary_coordinates = boundary_coordinates.concat(point.geometry.coordinates)
10 });
11
12 //setting the GEOJSON object required for the map display
13 //choosing the first route object to give us a quick GeoJSON-ready object
14 routes_arr[0].geometry.coordinates = boundary_coordinates
15 let mapGeoJsonObj = routes_arr[0]
16
17 drawMap(targetMap, boundary_coordinates, mapGeoJsonObj)
18
19 }

Just like the previous code, we use an async await function to get the responses and then process the coordinates. Since GeoJSON objects are needed for the map display, we will need to create one. The response from Snap-to-roads returns many of them in individual snapped segments, so we need to extract the coordinates and set them to one object. Instead of writing, a string, appending the coordinates, and converting it to JSON format, we will use a simpler option. We take advantage of GeoJSON objects returned by the API. We choose one snapped segment and set the extracted coordinates to it using this line.

routes_arr[0].geometry.coordinates = boundary_coordinates

Note that the coordinates will be used to set the map’s boundaries, that’s why we named them boundary_coordinates.

To display the map, we’ll use a helper function to avoid long code in the snap_to_roads function.

Below is the code for drawing the map:

1async function drawMap(targetMap, boundaryCoords, geojsonObj) {
2 try {
3 setMapBounds(targetMap, boundaryCoords)
4 targetMap.addLayer({
5 'id': 'routeDemo',
6 'type': 'line',
7 'source': {
8 'type': 'geojson',
9 'data': geojsonObj
10 },
11 'paint': {
12 'line-color': '#ff0000',
13 'line-width': 8
14 }
15 });
16 } catch (e) {
17 console.log(e)
18 }
19 }

We start with setting the map bounds of the map section we want to display. We use a function called setMapBounds which we’ll look at later.

The map contains a method called addLayer, which is used to add map layers to an existing map. We’ll use it to add a road marking layer to denote the reconstructed road. First, we add a layer ID and the type. Next, a source object representing the data to be added to the layer is added. Finally, a color and line width are added using an object called paint.

Below is the setMapBounds method:

1 function setMapBounds(targetMap, coordinatesObj) {
2 let mapBounds = new mapSDK.LngLatBounds();
3 coordinatesObj.forEach((point) => {
4 mapBounds.extend(mapSDK.LngLat.convert(point));
5 });
6 targetMap.fitBounds(mapBounds, { duration: 0, padding: 50 });
7 }

We start by creating a LngLatBounds object called mapBounds. Next, we extract points from the GeoJSON data from the call to the calculateRoute method.

The mapBounds extend method zooms the map to the appropriate level depending on the points passed to it. The points should be in the LngLat object format. That’s why we convert each point first using the LngLat.convert method.

Finally, we fit the map to the set bounds using the fitBounds method. This method takes the map’s bounds as the first parameter and the options object as the last parameter. The options object is used to set an animation duration and the padding around the map.

To load the map on the page load, we need a useEffect hook. Add it using the code below:

1 useEffect(() => {
2 let ourMap = mapSDK.map({
3 key: API_KEY,
4 container: mapContainer.current,
5 zoom: zoomLevel
6 });
7 setMap(ourMap);
8 ourMap.on('load', 'routeDemo' ,mainProcessor(ourMap));
9 return () => ourMap.remove();
10 }, []);

The map is initialized using the Map SDK while passing in the API key, the container for rendering the map, and the zoom level. We also call our mainProcessor method here to perform what we’ve discussed. We then remove the map during a reload to recreate a fresh one.

The image below will be rendered upon running the app:

image 6

Conclusion

In this tutorial, we learned about the Snap to Roads API and then saw how to integrate it into a React app. In the integration process, we discussed the API further. Some observations we made are:

  • Provide enough coordinates.
  • Check your inputs to the request body.

Now that you have a roadmap, try the API out yourself. You can display information about a route using popups, display traffic information, and do many other wonderful things using the Snap to Roads API.

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