After so much time in lockdown, a road trip sounds particularly appealing to many people right now. But no one wants to waste time stuck in traffic or caught in unpleasant weather conditions on their drive.

Wouldn’t it be nice to have a tool that alerts you to road risks in advance?

That’s why I decided to build an app to show you information about road risk based on the current location of the user. 

Using the Tomorrow.io Weather API, your app can include road risk based on current weather conditions on your route, at the exact moment you’ll be traveling on that road.

The API returns a road risk score for a given geographical location.

road risk weather api Tomorrow.io

Road Risk API

The application I built is able to get my current location and show my geographical coordinates. Based on these coordinates, it will show road risk weather conditions, a confidence score for these conditions, and the road risk score (the one in the picture above). 

In the end, the application looks like this:

road risk app

The App

 

Obviously the UI is super basic, but the functionality can be integrated into your existing app easily. If you think that this kind of application is interesting and you want to know how I built it, then keep reading.

How to Build an App That Tracks Road Risk

The code base of the app is small in size. It has only one file index.html and a total of approximately 120 lines of code.

Building the UI

As a personal preference, when making an application or any other website, I choose to first create the user interface with fake data and then add logic and bring real data.

In this way, we will create the elements using HTML and then we will add that style.

The layout of the application can be split in two. The box with the current latitude and longitude, visible in the top right corner, and the content in the center with the road risk score.

Based on this, I created the following HTML elements and grouped them in two divisions. 

<div class="pos-wrapper">
  <p>Lat: <span id="lat"></span></p>
  <p>Lon: <span id="lon"></span></p>
</div>

<section>
  <span class="small-text"> Risk Conditions:</span>
  <span class="big-text" id="risk-condition"></span>
  <span class="small-text confidence" id="confidence"></span>

  <hr />

  <span class="small-text"> Risk Score:</span>
  <span class="big-text" id="risk-score"></span>
</section>

I prefer to use HTML tags and classes to select elements with CSS and apply code and to keep ids to be used only by the JavaScript code. In this way, the CSS logic and the hierarchy of the style applied to elements is easier to maintain.

Elements with the id `lat` and `lon` will be used to interpolate the current latitude and longitude.

The other ids `risk-condition`, `confidence` and `risk-score` are used to interpolate the data returned by Tomorrow.io API.

To make these HTML elements look like the one in the picture above, we’ll need to apply the following style.

html,
body {
  height: 100%;
}
body {
  margin: 0;
  padding: 15px;
  font-family: "Lato", sans-serif;
  color: #343434;
  font-weight: bold;
  text-align: center;
}

* {
  box-sizing: border-box;
}
.pos-wrapper {
  text-align: right;
}

.pos-wrapper > p {
  margin: 5px 0;
}

.small-text {
  font-size: 11px;
  text-transform: lowercase;
}

.big-text {
  font-size: 24px;
}

section {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: absolute;
}

.confidence::after {
  content: "%)";
  display: inline;
}

.confidence::before {
  content: "(";
  display: inline;
}

The Logic

Now that we have the foundation of the application, we are ready to collect real data and display it in our app.

I created a function whose purpose is to call the API and get road risk-related information.

async function getRoadRisk(lat, lon, key) {
  const url = `https://api.www.tomorrow.io/v3/weather/realtimelat=${lat}&lon=${lon}&fields=road_risk_score&fields=road_risk_confidence&fields=road_risk_conditions&apikey=${key}`;

  const res = await fetch(url);
  const data = await res.json();
  return data;
}

To use the API we need to provide the geographical coordinates of a location, latitude and longitude, and a private API key, which we acquire freely when we create an account on the Tomorrow.io platform.

If we call this function, the JSON data returned has the following structure:

getRoadRisk() – data output

We chose the indicators for which we want to get data for in the `url` of the requests as an array of strings:

`fields=[``'``road_risk_score``'``,` `'``road_risk_confidence``'``, 'road_risk_conditions``'``]`

Now we need to show this information on the UI, along with our current position.

function updateRoadRisk() {
  navigator.geolocation.getCurrentPosition(async (pos) => {
    const crd = pos.coords;

    document.querySelector("#lat").innerHTML = crd.latitude;
    document.querySelector("#lon").innerHTML = crd.longitude;

    const data = await getRoadRisk(crd.latitude, crd.longitude, CC_KEY);

    document.querySelector("#risk-condition").innerHTML =
      data.road_risk_conditions.value;
    document.querySelector("#confidence").innerHTML =
      data.road_risk_confidence.value;

    document.querySelector("#risk-score").innerHTML =
      data.road_risk_score.value;
  });
}

Fortunately, the browsers provide an API, named `navigator`, with which we can get the current location of the client.

The variable `CC_KEY` is a global constant that I defined and it holds my private API key.

The workflow of this function, updateRoadRisk() is pretty straightforward. We get the location of the user, display it on the UI, then we get the road risk information from the API, and display it on the UI as well.

This information must be real-time data, so we must call this function at a regular interval.

We’ll call this function, when the app first loads and then we’ll call it again every 2 minutes.

function () {
      updateRoadRisk();
    
      setInterval(() => {
        updateRoadRisk();
      }, 2 * 60 * 1000);
    })();

Conclusion 

The application is done, and you can start using it right now. If you’d like, you can use an easy-to-set-up hosting service which provides a free plan as well and deploy your application so you can access it from anywhere. And that is how you integrate road risk data from a weather API into your app.