CO₂ Emissions Calculator for Business Trips
The CO₂ Emissions Calculator is a web tool that estimates the carbon footprint of business trips by calculating CO₂ emissions from travel and accommodation. Users input trip details like service center and client locations, transportation mode, number of travelers, travel distance, and hotel nights. The calculator then provides a detailed breakdown of emissions for each trip segment.
Project Overview
The CO₂ Emissions Calculator is a dynamic web application designed to help users calculate the carbon footprint of their travel and accommodation. The tool integrates interactive maps, real-time calculations, and customizable user inputs to estimate CO₂ emissions based on various factors such as distance traveled, mode of transport, number of travelers, and the duration of hotel stays. This project showcases advanced frontend development skills, including responsive design, API integration, and mathematical computation.
Key Features
Interactive Mapping: Users can select geographic locations directly on interactive maps, which automatically updates latitude and longitude values.
Dynamic Input Handling: The application handles multiple user inputs, recalculating emissions in real-time based on changing data.
Emission Breakdown: Provides a detailed breakdown of emissions by travel and hotel stay, giving users clear insights into their carbon footprint.
Customizable Scenarios: Users can adjust travel modes, number of travelers, and hotel stays to see how different scenarios impact CO₂ emissions.
Technologies Used
Frontend: HTML5, CSS3, JavaScript (ES6+)
Libraries: Leaflet.js for map interaction, OpenStreetMap for map tiles, and vanilla JavaScript for logic handling
Responsive Design: CSS Flexbox, Media Queries
APIs: OpenStreetMap for map data, integrated via Leaflet.js
Code Implementation
1. HTML Structure
The application is structured within a div container, with two primary sections for the service center and client location maps, along with various input fields for travel and accommodation details.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CO₂ Emissions Calculator</title>
<!-- Styles and scripts will be linked here -->
</head>
<body>
<div class="container">
<!-- Main content goes here -->
</div>
</body>
</html>
Here, we set up the basic HTML document with essential meta tags to ensure proper character encoding and responsiveness across different devices. The container div is introduced to encapsulate the main content of the application.
2. Styling: Enhancing the User Experience
To create a clean and modern user interface, CSS is used to style the elements on the page. That way we will give the body a soft, off-white background and centers the main container both vertically and horizontally. In addition, the container has a nice shadow to make it pop off the page, making the calculator feel like a polished, professional tool.
3. The Interface: Inputs for the User
The next step is to create the user interface, where users can input data such as latitudes, transport mode, and other necessary parameters.
<div class="container">
<h1>CO₂ Emissions Calculator</h1>
...
<div class="form-group">
<label for="lat1">Latitude of Service Center</label>
<input type="number" id="lat1" name="lat1" step="any" required>
</div>
<div class="form-group">
<label for="lon1">Longitude of Service Center</label>
<input type="number" id="lon1" name="lon1" step="any" required>
...
</div>
<div class="form-group">
<label for="transport">Mode of Transport:</label>
<select id="transport" name="transport">
<option value="plane">Plane</option>
<option value="car">Car</option>
<option value="train">Train</option>
</select>
</div>
<button type="button" onclick="calculateEmissions()">Calculate CO₂ Emissions</button>
<p id="result"></p>
</div>
In this section, several input fields are provided to gather the necessary information from the user. These include latitude and longitude coordinates for both the service center and client locations, as well as the transport mode. A button is included to trigger the calculation, with the results displayed in the result paragraph.
4. JavaScript Logic: Implementing the Core Functionality
Now, let’s move on to the core functionality of the application—calculating the CO₂ emissions based on the user input. The following JavaScript handles this:
<script>
function calculateEmissions() {
const lat1 = parseFloat(document.getElementById('lat1').value);
const lon1 = parseFloat(document.getElementById('lon1').value);
const lat2 = parseFloat(document.getElementById('lat2').value);
const lon2 = parseFloat(document.getElementById('lon2').value);
const transport = document.getElementById('transport').value;
if (isNaN(lat1) || isNaN(lon1) || isNaN(lat2) || isNaN(lon2)) {
alert("Please enter valid coordinates.");
return;
}
const R = 6371; // Radius of Earth in kilometers
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c; // Distance in kilometers
let emissionsPerKm;
switch (transport) {
case 'plane':
emissionsPerKm = 0.115; // kg CO₂ per km per passenger for plane
break;
case 'car':
emissionsPerKm = 0.21; // kg CO₂ per km for car
break;
case 'train':
emissionsPerKm = 0.041; // kg CO₂ per km per passenger for train
break;
default:
emissionsPerKm = 0;
}
const totalEmissions = distance * emissionsPerKm;
document.getElementById('result').textContent = `Total CO₂ Emissions: ${totalEmissions.toFixed(2)} kg`;
}
</script>
Breakdown of the JavaScript Logic:
Input Validation: The script begins by retrieving and parsing the user inputs. If any inputs are invalid, an alert is triggered to notify the user.
Distance Calculation: The Haversine formula is applied to calculate the great-circle distance between the two points on Earth. This formula accounts for the spherical shape of the planet, providing an accurate distance in kilometers.
CO₂ Emission Calculation: Depending on the mode of transport selected by the user, a specific emission factor (in kg CO₂ per km) is applied. The total emissions are calculated by multiplying this factor by the distance.
Displaying Results: The calculated CO₂ emissions are then displayed in the result element, providing the user with their total emissions in kilograms.
5. Interactive Features: Enhancing Usability with Maps
To further enhance the user experience, a map interface is integrated using the Leaflet library. This allows users to click on the map to set their coordinates automatically.
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script>
function initMap(mapId, latInputId, lonInputId) {
const map = L.map(mapId).setView([0, 0], 2);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
let marker;
map.on('click', function (e) {
const { lat, lng } = e.latlng;
document.getElementById(latInputId).value = lat.toFixed(6);
document.getElementById(lonInputId).value = lng.toFixed(6);
if (marker) {
marker.setLatLng(e.latlng);
} else {
marker = L.marker(e.latlng).addTo(map);
}
});
}
document.addEventListener('DOMContentLoaded', function () {
initMap('map1', 'lat1', 'lon1');
initMap('map3', 'lat3', 'lon3');
});
</script>
In this script:
The initMap function initializes a Leaflet map and sets its view to show the entire world initially.
A tile layer from OpenStreetMap is added to provide the map imagery.
An event listener is added to the map to handle click events. When the map is clicked, the latitude and longitude of the click location are set as the values of the corresponding input fields, and a marker is placed or moved to the click location.
This integration of interactive maps significantly improves the usability of the CO₂ Emissions Calculator by providing a more intuitive way for users to input location data.
Summary
In the CO₂ Emissions Calculator, the integration of interactive maps using the Leaflet library significantly enhances user experience. By allowing users to click on the map to automatically set their coordinates, this feature minimizes input errors and speeds up data entry. The maps make the process more engaging and intuitive, ultimately providing a more user-friendly interface. This enhancement ensures accurate and efficient data input for calculating CO₂ emissions, contributing to a more reliable and enjoyable user experience.
Find the full code in the following txt file: