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:
Maps SDK for Web
Maps SDK for Android
Maps SDK for iOS
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 service |
{versionNumber} | // version of the service to |
/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.
For the second example use case for adding Traffic APIs to your app, please read the rest of this article on TomTom's Developer Blog.
Top comments (3)
Oddly enough, but for the application for our website of legal online casinos source for the implementation of the API in our app was this article, the excellent information provided made it possible to do everything easily and quickly.
Is it possible to implement this API in a symphony framework? Examples of old one you can see there - (PL one) fxmag and also there (spanish example) - es.fxmag or in a new edition of FXMAG.
Hi, I have a Dailymotion account and need crazy traffic, please assist me