Codementor Events

Building a Real-Time Air Quality Monitoring Dashboard with Ambee's Air Quality API

Published Nov 24, 2023

In an era where environmental consciousness is at its peak, creating tools that empower individuals with real-time air quality information is both relevant and impactful. In this tutorial, we'll dive into the process of building a dynamic dashboard that monitors air quality using Ambee's air quality API. By the end of this guide, you'll have a fully functional, user-friendly interface that provides up-to-the-minute air quality data.

Introduction
The Importance of Air Quality Monitoring
Air quality is a critical factor affecting public health and well-being. Poor air quality can lead to respiratory issues and other health problems. Real-time monitoring is essential for individuals, local communities, and policymakers to make informed decisions regarding outdoor activities and environmental regulations.

About Ambee's Air Quality API
Ambee's air quality API is a powerful tool that provides access to accurate and real-time air quality data. With endpoints for various pollutants and location-based information, it's an ideal choice for developers looking to integrate air quality monitoring into their applications.

Prerequisites
Before we start building the dashboard, let's ensure we have everything we need:

Ambee API Key: Sign up on Ambee's website to obtain your API key.
Code Editor: Use your preferred code editor; Visual Studio Code, Sublime Text, or Atom are popular choices.
Basic Web Development Knowledge: Familiarity with HTML, CSS, and JavaScript.
Step 1: Setting Up the Project
Create a new project folder and initialize it with the necessary files:

mkdir air-quality-dashboard
cd air-quality-dashboard
touch index.html styles.css script.js

Step 2: HTML Structure
Let's start with the HTML structure for our dashboard. Open index.html in your code editor and add the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <title>Air Quality Dashboard</title>
</head>
<body>
    <div class="container">
        <!-- Content will go here -->
    </div>
    <script src="script.js"></script>
</body>
</html>

Step 3: Styling the Dashboard
Open styles.css and add basic styling to our dashboard:

body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
}

.container {
    max-width: 800px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

/* Add more styles as needed */

Step 4: Fetching Data with JavaScript

In script.js, let's start by fetching air quality data from Ambee's API:

const apiKey = 'YOUR_API_KEY';
const apiUrl = 'https://api.ambeedata.com/air-quality/v1';

async function getAirQualityData(latitude, longitude) {
    try {
        const response = await fetch(`${apiUrl}/latest/by-lat-lng?lat=${latitude}&lng=${longitude}`, {
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': apiKey,
            },
        });

        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching air quality data:', error);
    }
}

// Replace with the desired location coordinates
const latitude = 37.7749;
const longitude = -122.4194;

getAirQualityData(latitude, longitude)
    .then(data => {
        console.log('Air quality data:', data);
        // Display data on the dashboard
    });

Step 5: Displaying Data on the Dashboard

Now, let's update our index.html to display the fetched air quality information:

<!-- Inside the .container div -->
<div id="airQuality">
    <h2>Air Quality Information</h2>
    <p id="location">Location: <span id="locationData"></span></p>
    <p id="aqi">AQI (Air Quality Index): <span id="aqiData"></span></p>
    <!-- Add more information as needed -->
</div>

Update script.js to dynamically populate this information:

// Inside the getAirQualityData function
function displayAirQuality(data) {
    const locationElement = document.getElementById('locationData');
    const aqiElement = document.getElementById('aqiData');

    locationElement.textContent = `${data.city}, ${data.state}, ${data.country}`;
    aqiElement.textContent = data.data.indexes.breezometer.aqi;

    // Add more elements and data as needed
}

// Inside the .then block
.then(data => {
    console.log('Air quality data:', data);
    displayAirQuality(data);
});

Step 6: Real-Time Updates
To make our dashboard real-time, we can set up periodic updates. Add the following code inside the .then block:

// Update every 5 minutes (adjust as needed)
setInterval(() => {
    getAirQualityData(latitude, longitude)
        .then(data => {
            console.log('Air quality data:', data);
            displayAirQuality(data);
        });
}, 300000);

// Update every 5 minutes (adjust as needed)
setInterval(() => {
    getAirQualityData(latitude, longitude)
        .then(data => {
            console.log('Air quality data:', data);
            displayAirQuality(data);
        });
}, 300000);

Conclusion
Congratulations! You've successfully built a real-time air quality monitoring dashboard using Ambee's air quality API. This project forms a solid foundation that you can expand upon by adding more features, such as historical data analysis, geospatial visualization, or integration with other APIs.

Remember to keep your API key secure, especially if you plan to deploy this dashboard. Feel free to explore additional capabilities of Ambee's API and customize the dashboard to meet your specific requirements. Happy coding!

Discover and read more posts from Liam Jones
get started
post commentsBe the first to share your opinion
Show more replies