GreenRoute is a modern, sustainable navigation web application designed to help users reduce their carbon footprint. Unlike traditional navigation apps that prioritize speed above all else, GreenRoute calculates and suggests the most environmentally friendly routes between two locations.
"The greatest threat to our planet is the belief that someone else will save it." โ Robert Swan
- ๐ The "Why" - A Deeper Look
- ๐๏ธ System Architecture
- ๐ Comprehensive User Guide
- ๐ป Code Deep Dive & Pattern Analysis
- โจ Key Features
- ๐ธ Screenshots
- ๐ Tech Stack
- ๐ Getting Started
- ๐ Folder Structure
- ๐ข Deployment
- ๐ฎ Roadmap
- ๐ง Troubleshooting
- ๐ค Contributing
- ๐ License
Modern navigation algorithms (Google Maps, Waze) are optimized for one single metric: Time. They will happily route you 5 miles further to save 1 minute of travel time.
However, Distance โ Emissions.
- Stop-and-go traffic emits 2-3x more COโ than highway driving.
- A slightly longer route at a steady speed is often greener than a shorter, congested one.
- Taking a bus instead of a car reduces emissions by ~66%.
Transportation accounts for 24% of direct COโ emissions from fuel combustion. GreenRoute empowers users to visualize this impact.
| Mode of Transport | COโ per Mile (Avg) | Impact Level |
|---|---|---|
| ๐ SUV / Truck | 360g | ๐ด High |
| ๐ Sedan | 192g | ๐ Medium |
| ๐ Public Transit | 64g | ๐ก Low |
| ๐ฒ Cycling | 0g | ๐ข Zero |
| ๐ถ Walking | 0g | ๐ข Zero |
GreenRoute follows a Client-Side Rendering (CSR) architecture powered by React and APIs.
graph TD
A[User Interaction] -->|Inputs Locations| B(React Frontend)
B -->|Geocoding Request| C[Mapbox Geocoding API]
C -->|Coordinates| B
B -->|Directions Request| D[Mapbox Directions API]
D -->|Route Data (GeoJSON)| B
B -->|Calculate Emissions| E[Utility Logic]
E -->|Green Score| F[Zustand State Store]
F -->|Update UI| G[Map & Info Cards]
- Input Layer: Users interact with the search bar using
Mapbox Geocoder. - Data Layer: We fetch routes for multiple profiles (
driving,cycling,walking). - Logic Layer: Raw distance/duration data is passed to
emissions.tsto append carbon data. - Presentation Layer: Mapbox GL JS renders the lines; React renders the UI overlay.
The UI is split into two main layers:
- Background: The interactive 3D map.
- Foreground: The glass-morphism control panel (Desktop: Top-Left, Mobile: Bottom-Sheet).
- Grant Permissions: Allow Geolocation for the best experience.
- Set Origin: Defaults to your location. Click the "Current Location" icon to reset.
- Set Destination: Use the search bar. It supports "Fuzzy Search" (e.g., typing "coffee near me").
- Analyze Routes:
- The Leaf Icon ๐: Indicates the most eco-friendly route, even if it's not the fastest.
- The Flame Icon ๐ฅ: Indicates high fuel consumption (avoid if possible).
The Green Score (0-100) is our proprietary efficiency rating.
- 90-100: Excellent (Walking/Biking or very efficient driving).
- 70-89: Good (Standard transit or direct driving).
- < 50: Poor (Inefficient route, heavy traffic, or high-emission vehicle).
The app caches the core assets using a Service Worker (via Vite PWA plugin). If you lose internet, you can still view the map tiles that were previously loaded, though routing APIs will be unavailable.
We use zustand for global state to avoid "Prop Drilling".
File: src/store/useRouteStore.ts
import create from 'zustand';
interface RouteState {
origin: Coordinates | null;
destination: Coordinates | null;
routes: RouteData[];
setRoutes: (routes: RouteData[]) => void;
}
export const useRouteStore = create<RouteState>((set) => ({
origin: null,
destination: null,
routes: [],
setRoutes: (routes) => set({ routes }),
}));To keep components clean, map logic is extracted into hooks.
File: src/hooks/useMapbox.ts
export const useMapbox = (containerRef: RefObject<HTMLDivElement>) => {
useEffect(() => {
if (!containerRef.current) return;
const map = new mapboxgl.Map({
container: containerRef.current,
style: 'mapbox://styles/mapbox/streets-v11',
center: [-74.5, 40],
zoom: 9
});
return () => map.remove();
}, []);
};We calculate CO2 based on distance and estimated traffic drag (duration vs distance ratio).
File: src/utils/emissions.ts
export const calculateCO2 = (distance: number, duration: number, mode: string) => {
const BASE_EMISSION = 120; // g/km for cars
const TRAFFIC_PENALTY = 10; // g/min of delay
let totalCO2 = (distance / 1000) * BASE_EMISSION;
// If speed is below 20km/h (traffic), add penalty
const speed = (distance / 1000) / (duration / 3600);
if (mode === 'driving' && speed < 20) {
totalCO2 += (duration / 60) * TRAFFIC_PENALTY;
}
return Math.round(totalCO2);
};| Feature | Description | Status |
|---|---|---|
| ๐ฑ Eco-Routing | Prioritizes lower emissions using our custom algorithm. | โ Live |
| ๐ฒ Multi-Mode | Compare Car, Bus, Bike, and Walking in one view. | โ Live |
| ๐ Green Score | Visual 0-100 efficiency rating. | โ Live |
| ๐ Dark Mode | Auto-adapts to system preferences. | โ Live |
| ๐ Auth & Cloud | Save routes and history via Firebase. | โ Live |
| ๐พ PWA | Installable on iOS/Android. | ๐ง Beta |
| ๐ EV Stations | Find charging spots along the route. | ๐ Coming Soon |
| Landing Page | Route Calculation | Dark Mode |
|---|---|---|
- Framework: React 18 (TypeScript)
- Build Tool: Vite (Fast HMR)
- Styling: Tailwind CSS + Headless UI (Accessible components)
- Icons: Heroicons / Phosphor Icons
- Core Map: Mapbox GL JS
- Routing: Mapbox Directions API
- Geocoding: Mapbox Geocoding API
- Auth: Firebase Authentication (Google/Email)
- Database: Cloud Firestore (NoSQL)
- Hosting: Netlify / Vercel
- Node.js v16+
- Mapbox Account (for API Token)
-
Clone & Install
git clone https://github.com/demon2202/GreenRoute.git cd GreenRoute npm install -
Configure Environment Create a
.env.localfile in the root:VITE_MAPBOX_TOKEN=pk.eyJ1IjoiZ... (Your token here) VITE_FIREBASE_API_KEY=AIzaSy... VITE_FIREBASE_AUTH_DOMAIN=greenroute.firebaseapp.com VITE_FIREBASE_PROJECT_ID=greenroute
-
Run Development Server
npm run dev
Visit
http://localhost:5173.
GreenRoute/
โโโ src/
โ โโโ assets/ # Static images/fonts
โ โโโ components/
โ โ โโโ layout/ # Header, Sidebar, Footer
โ โ โโโ map/ # MapCanvas, Markers, Popups
โ โ โโโ routing/ # RouteCard, TransportSelector
โ โ โโโ ui/ # Buttons, Inputs, Modals
โ โโโ context/ # React Context providers
โ โโโ hooks/ # Custom hooks (useAuth, useGeo)
โ โโโ pages/ # Dashboard, Login, Settings
โ โโโ services/ # API wrapper functions
โ โโโ styles/ # Global CSS/Tailwind directives
โ โโโ utils/ # Helpers (formatters, calculators)
โ โโโ App.tsx
โโโ ...config files
- Install Vercel CLI:
npm i -g vercel - Run
vercel - Set your Environment Variables in the Vercel Dashboard.
- Drag and drop the
distfolder (created afternpm run build) to Netlify Drop. - Or connect GitHub repo for auto-deploys.
- Basic Eco-Routing
- User Authentication
- Gamification: Leaderboards for CO2 saved.
- EV Support: Show charging stations.
- Carpooling: Match with users on similar routes.
- Weather: Alert if rain affects cycling routes.
Map is black/blank:
- Check if your Mapbox Token is valid.
- Ensure the
styleURL inMapCanvas.tsxis correct.
"Process is not defined":
- Since we use Vite, use
import.meta.env.VITE_VARinstead ofprocess.env.REACT_APP_VAR.
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.
Made with ๐ by demon2202