TomTom Traffic APIs
If you’re a developer, you probably already know why APIs are valuable—By integrating APIs into your project, you can greatly simplify and accelerate whatever you are building by taking advantage of solutions that have already been provided by industry leaders, and using the pre-existing code that they offer.
Traffic APIs are a great demonstration of the value of APIs for developers (not to mention end-users who can take advantage of API-powered traffic apps). Traffic APIs provide the building blocks for you to potentially craft better user experiences with real-time traffic data. You can build fun tools and applications and gain insight about traffic happenings.
TomTom is an industry leader in the realm of navigation, mapping, and traffic products, and continues to create influential, easy-to-use navigation systems. Over the years, the company has expanded its focus from device manufacturing to software development. And now, they have decided to share what they do best: advanced traffic information. TomTom produces innovative software and services and offers a comprehensive API that will allow you to retrieve detailed traffic information about an area.
In this article, we will dive into how TomTom’s Traffic API works and how we can leverage the Traffic suite of web services (which are based on the real-time traffic data from TomTom Traffic) to retrieve detailed traffic information about an area, which you can use for your web and mobile applications. We will be making use of some JavaScript with ReactJS, as well as bash scripting in the examples.
How Does TomTom Traffic Work?
TomTom Traffic API is a cloud-based, real-time traffic monitoring information service that detects traffic on highways and secondary roads, and it works because of billions of anonymized traffic measurements (GPS traces or probe data) from around the globe. The service has existed for a decade, and the company has access to a lot of Big Data about where, when, and how people drive all over the world.
In order to provide this quality service, data is combined from traditional sources (e.g. road induction loops, traffic surveillance cameras), modern sources (e.g. data from millions of anonymous mobile phone users), and historical data. The information is then collated by TomTom data centers for further filtering and improvements before it gets distributed to its customers as relevant, real time traffic information, with updates sent every two minutes. The traffic data is reliable, accurate, frequent, and has wide coverage. A lot of details (e.g. traffic jams, road closures, delays) are provided, even for smaller roads.
With the quality of TomTom’s traffic data in mind, we can be confident about creating useful, reliable and high-quality applications through the use of their Traffic API suite, which is based on this data.
Getting Started with TomTom and the Traffic API
The Traffic API is a suite of web services that can let you to unleash your creativity by building user-friendly applications with real-time traffic data. The service is built with developers in mind, can be used via RESTful APIs, and has very wide market coverage.
The TomTom Developer Portal is where you’ll find everything you need to get up and running with this API. The first thing you’ll want to do is create an account on the portal. From the home page, enter your email address and click on the “Get a free API key” button.
Once you have signed up or logged in, create a new app to receive your API key. Applications require a name, and you’ll need to enable the APIs which the application needs to access. For this example, the product we’ll be using are the Traffic Flow API and the Traffic Incidents API. If you’re following along, select the Traffic Flow API and the Traffic Incidents API products and click on Create App.
The Traffic Incidents API provides accurate information about traffic jams, incidents, accidents, and delays surrounding an area that you can display on a map. The Traffic Flow APIs provide information about observed speeds (current, freeflow) and travel times for specific road networks.
This article focuses on how to use the TomTom Traffic Flow and Traffic Incident APIs, but developers also have access to Web and Mobile SDKs which contain similar functionality. You can learn more about each of the SDKs from the following links:
Example Use Case #1
Let’s find the location of a user and then display real-time traffic jams and incident data based on where they are. When the user is on a mobile device (even when they are just connecting to a website and not using a native app), you can ask for their GPS position. In this example, we will just locate the user based on their IP address.
We will be using the Traffic Incident Details API from the Traffic Incident API suite. The request URL for this API is in this format:
https://api.tomtom.com/traffic/services/{versionNumber}/incidentDetails/{style}/{boundingBox}/{zoom}/{trafficModelID}/{format}?key={API_KEY}&language={string}&projection={string}&geometries={string}&expandCluster={boolean}&originalPosition={boolean}
Let’s dig a little deeper into what each parameter means.
https://api.tomtom.com
/traffic/services // traffic services
/{versionNumber} // version of the service to call
/incidentDetails // incident details service
/{style} // style of tile to be rendered
/{boundingBox} // bottom-left latitude,
bottom-left longitude,
top-right latitude,
top-right longitude
/{zoom} // zoom level
/{trafficModelID} // traffic model ID (default -1)
/{format} // xml, json, jsonp
?key={API_KEY} // API key
&language={string} // language of descriptions
&projection={string} // type of coordinate system
(EPSG900913 or EPSG4326)
&geometries={string} // type of vector geometry added to
incidents
&expandCluster={boolean} // send clustered points
&originalPosition={boolean} // return original position of
incident and the one shifted to
beginning of traffic tube
An example response based on this request:
{
"tm": {
"@id": "1537875895566",
"poi": [
{
"id": "europe_CLUSTER_9_-1546746781",
"p": {
"x": 11.368265,
"y": 48.002922
},
"ic": 13,
"ty": 1,
"cbl": {
"x": 11.28824,
"y": 47.969362
},
"ctr": {
"x": 11.44829,
"y": 48.03646
},
"cs": 13,
"l": 27210
},
{
"id": "europe_HD_DE_TTR131344535899136",
"p": {
"x": 11.237004,
"y": 48.082583
},
"ic": 9,
"ty": 1,
"cs": 0,
"d": "roadworks",
"c": "new roadworks layout",
"f": "Wörthsee (A96)",
"t": "Germering-Süd (A96)",
"l": 5840,
"dl": 113,
"r": "A96/E54"
}
]
}
}
Now that we have a better understanding of how to consume the API, let’s try to build a simple app with it. We can use ReactJS to consume the API and manipulate the data like so:
INDEX.JS
import React, { Component } from "react";
import ReactDOM from "react-dom";
import publicIP from "public-ip";
import geoPoint from "geopoint";
import IncidentCategory from './components/incident_category';
import IncidentData from './components/incident_data';
import IncidentLegend from './components/incident_legend';
// Your API KEY can be hardcoded, but I recommend setting it as an env variable.
const API_KEY = '*****';
class App extends Component {
constructor() {
super();
this.state = {
error: null,
isLoaded: false,
trafficData: []
};
}
componentDidMount() {
publicIP.v4()
.then(ip => fetch(`https://ipapi.co/${ip}/json`))
.then(res => res.json())
.then(result => this.getBoundingBox(result.latitude, result.longitude))
.then(
values =>
fetch(`https://api.tomtom.com/traffic/services/4/incidentDetails/s3/${values[0]._degLat},${values[0]._degLon},${values[1]._degLat},${values[1]._degLon}/10/-1/json?key=${API_KEY}&projection=EPSG4326`)
)
.then(res => res.json())
.then(
payload => {
this.setState({
isLoaded: true,
trafficData: payload["tm"]["poi"]
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
)
}
getBoundingBox(latitude, longitude) {
const bboxValues = new geoPoint(latitude, longitude).boundingCoordinates(10, true);
return bboxValues;
}
render() {
const { error, isLoaded, trafficData } = this.state;
let date = new Date();
let currentDate = date.toDateString();
let currentTime = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
if (error) {
return
Error: {error.message};
}
else if (!isLoaded) {
return Loading...;
}
else {
return (
Traffic Incidents
{currentDate}
Time: {currentTime}
COMPONENTS/INCIDENT_DATA.JS
import React from 'react';
const IncidentData = (props) => {
const incidents = props.data;
return (
{incidents.map((el) => {
return (
{el["p"]["x"]}, {el["p"]["y"]} // location
{el["l"]} // length of delay
{el["d"]} // description
{el["ic"]} // type
{el["ty"]} // severity
)
})}
);
};
export default IncidentData;
More of the code can be viewed here: https://sourcegraph.com/github.com/infoverload/trafficincidents@f8ea4e88ea5471f7a91bbc3161c3390afbcbe3d8/-/blob/src/index.js The result in the browser looks like:
Example Use Case #2
A more no-frills way that we can interact with the TomTom API is to integrate it into a CLI tool. Let’s use one of the APIs from the Traffic Flow API suite in this example. The Flow Segment Data API provides information about the speeds and travel times of a road segment based on the coordinates provided.
The request URL for this API is in this format:
https://api.tomtom.com/traffic/services/{versionNumber}/flowSegmentData/{style}/{zoom}/{format}?point={latitude},{longitude}&unit={string}&thickness={integer}&openLr={boolean}&key={API_KEY}
We could write a basic bash script that accepts a latitude and longitude value as the input:
#!/bin/bash
echo "---------- Traffic Flow Segment Data -----------"
echo "This service provides information about the speeds and travel times of the road segment closest to the given coordinates."
bail() {
echo "${1}"
exit 1
}
check_floating_point() {
[ $(echo ${1} | grep "^[0-9]*[.][0-9]*$") ] || bail "Invalid input. Try again."
}
read -p "Latitude: " latitude
check_floating_point ${latitude}
read -p "Longitude: " longitude
check_floating_point ${longitude}
echo "Here is the traffic flow segment data for the area near ${latitude} and ${longitude}"
curl --silent "https://api.tomtom.com/traffic/services/4/flowSegmentData/absolute/10/json?point=${latitude}%2C${longitude}&key=*****" -H "accept: */*" | jq
The result would be something like:
Disclaimer & Other Use Cases
The provided examples serve to merely give you an idea of how you could incorporate and consume the API, and aren’t examples of production-ready usage. There are countless other ways to build upon them.
Moreover, note that this article has explored only some of the APIs offered in the Traffic API Service. There are many more APIs out there that can do other things, such as indicate the severity of current traffic conditions, or the accurate location of slowdowns (with colored tubes over a TomTom map). You could also build a more comprehensive Traffic Management Monitoring application with the traffic incident and flow speed information offered by the TomTom API, combined with other traffic-relevant, real-time open data on the Web. The possibilities are endless! But, as always, make sure to be a responsible API consumer and design your system in a way that plays nicely with other services.
This article originally appeared on https://developer.tomtom.com/blog. The original author is Daisy Tsang.
Top comments (0)