# 🗺️ Route Tracker — Google Maps Route Statistics Collector

Automatically collects Google Maps Directions API data for your son's trips to the learning center, building statistics over time to find the **best route by day, time, and season**.

## Route Schedule

| Day       | Departure | From                          | To                           |
|-----------|-----------|-------------------------------|------------------------------|
| Monday    | 16:00     | Ελλησπόντου 61, Νέα Σμύρνη   | Μακρυγιάννη 100, Μοσχάτο    |
| Thursday  | 18:00     | Same                          | Same                         |
| Friday    | 17:00     | Same                          | Same                         |

## Architecture

```
collector.php  ──(cron)──→  Google Maps Directions API
       │                            │
       └──── SQLite DB ◄────────────┘
                 │
       api.php ──┘
         │
   dashboard.html  (browser)
```

## Setup Instructions

### 1. Get a Google Maps API Key

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project (or use existing)
3. Enable **Directions API**
4. Create an API key in **Credentials**
5. (Recommended) Restrict the key to the Directions API only
6. (Recommended) Restrict by IP address to your server's IP

**Cost**: The Directions API costs $5 per 1000 requests. With 3 requests/week × 4 samples each = ~12/week = ~50/month ≈ **$0.25/month**.

### 2. Install on Your Linux Server

```bash
# Clone/copy files to your server
sudo mkdir -p /var/www/route-tracker
sudo cp -r * /var/www/route-tracker/
cd /var/www/route-tracker

# Set permissions
sudo chown -R www-data:www-data /var/www/route-tracker
sudo chmod 755 /var/www/route-tracker
sudo mkdir -p /var/www/route-tracker/data
sudo chmod 775 /var/www/route-tracker/data

# PHP requirements (Ubuntu/Debian)
sudo apt install php-cli php-sqlite3 php-curl
```

### 3. Configure

Edit `config.php`:

```php
define('GOOGLE_MAPS_API_KEY', 'AIzaSy...your-key-here...');
define('API_TOKEN', 'a-strong-random-string-here');
```

Also update the token in `dashboard.html`:
```javascript
const API_TOKEN = 'a-strong-random-string-here';
```

### 4. Initialize Database

```bash
php schema.php
```

### 5. Test API Connection

```bash
php collector.php --test
```

This will show the full API response without saving, so you can verify everything works.

### 6. Set Up Cron Jobs

```bash
crontab -e
```

Add these lines:

```cron
# Route Tracker — collect route data
# Monday at 15:45, 15:50, 15:55, 16:00, 16:05
45,50,55 15 * * 1 /usr/bin/php /var/www/route-tracker/collector.php >> /var/www/route-tracker/data/cron.log 2>&1
0,5 16 * * 1 /usr/bin/php /var/www/route-tracker/collector.php >> /var/www/route-tracker/data/cron.log 2>&1

# Thursday at 17:45, 17:50, 17:55, 18:00, 18:05
45,50,55 17 * * 4 /usr/bin/php /var/www/route-tracker/collector.php >> /var/www/route-tracker/data/cron.log 2>&1
0,5 18 * * 4 /usr/bin/php /var/www/route-tracker/collector.php >> /var/www/route-tracker/data/cron.log 2>&1

# Friday at 16:45, 16:50, 16:55, 17:00, 17:05
45,50,55 16 * * 5 /usr/bin/php /var/www/route-tracker/collector.php >> /var/www/route-tracker/data/cron.log 2>&1
0,5 17 * * 5 /usr/bin/php /var/www/route-tracker/collector.php >> /var/www/route-tracker/data/cron.log 2>&1
```

**Why multiple times?** Each cron run captures a separate API snapshot. Collecting 4-5 samples around the departure time gives you more data points and averages out momentary traffic fluctuations.

### 7. Web Server Setup (for Dashboard)

**Option A: PHP Built-in Server (quick test)**
```bash
cd /var/www/route-tracker
php -S 0.0.0.0:8080
# Then open http://your-server-ip:8080/dashboard.html
```

**Option B: Apache**
```apache
<VirtualHost *:80>
    ServerName routes.yourdomain.com
    DocumentRoot /var/www/route-tracker
    
    <Directory /var/www/route-tracker>
        AllowOverride None
        Require all granted
    </Directory>

    # Block direct access to data/config
    <Directory /var/www/route-tracker/data>
        Require all denied
    </Directory>
    <Files "config.php">
        Require all denied
    </Files>
</VirtualHost>
```

**Option C: Nginx**
```nginx
server {
    listen 80;
    server_name routes.yourdomain.com;
    root /var/www/route-tracker;
    index dashboard.html;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location /data/ { deny all; }
    location = /config.php { deny all; }
}
```

## How It Works

### Data Collection

Every scheduled time, the collector:

1. Calls Google Maps Directions API with `departure_time=now` (for real-time traffic)
2. Requests **alternative routes** (Google typically returns 2-3 options)
3. Stores for each route:
   - **Duration** (base + with traffic)
   - **Distance**
   - **Route summary** (main road name, e.g., "Pireos", "Syggrou")
   - **Turn-by-turn steps** with road names
4. Tags the data with day, time, week, month for analysis

### What Gets Tracked

The key metric is `duration_in_traffic_seconds` — this is Google's real-time estimate accounting for current traffic conditions. When unavailable, `duration_seconds` (base time without traffic) is used.

### Statistics & Analysis

The dashboard provides:

| Stat | What It Shows |
|------|---------------|
| **By Day** | Which day has the worst traffic (Thu 18:00 will likely be worst) |
| **By Month** | Seasonal patterns (summer holidays = less traffic, Sept/Oct = school rush) |
| **By Route** | Which road (Pireos vs Syggrou vs Hamosternas etc.) is consistently fastest |
| **Best Routes** | Per day-slot recommendation with consistency score |
| **Trends** | How travel time changes over weeks/months |

### Interpreting Results

After collecting data for a few weeks, you'll see patterns like:

- **Monday 16:00**: Moderate traffic — Route via X averages 12 min
- **Thursday 18:00**: Peak hour — Route via Y averages 18 min (avoid Route Z = 25 min)
- **Friday 17:00**: Variable — Route via X averages 14 min

The **consistency score** (duration range) tells you how predictable a route is. A route averaging 15 min with range ±2 min is more reliable than one averaging 13 min with range ±8 min.

## API Endpoints

All endpoints require `?token=YOUR_API_TOKEN`.

| Endpoint | Description |
|----------|-------------|
| `api.php?action=overview` | Summary statistics |
| `api.php?action=by_day` | Stats grouped by day of week |
| `api.php?action=by_month` | Stats grouped by month |
| `api.php?action=by_route` | Stats grouped by route name |
| `api.php?action=by_week` | Weekly trends |
| `api.php?action=timeline` | All data points (for charts) |
| `api.php?action=best_routes` | Best route recommendation per day |
| `api.php?action=heatmap` | Duration heatmap data |
| `api.php?action=collections` | Recent raw collections |

**Filters**: Add `&year=2025`, `&month=9`, `&day=1` (Mon) to any endpoint.

## File Structure

```
route-tracker/
├── config.php          # API key, schedule, settings
├── schema.php          # Database setup (run once)
├── collector.php       # Cron data collector
├── api.php             # JSON API for dashboard
├── dashboard.html      # Browser dashboard (vanilla JS)
├── README.md           # This file
└── data/
    ├── routes.sqlite   # SQLite database (auto-created)
    ├── collector.log   # Collection logs
    └── cron.log        # Cron output log
```

## Expected Findings for Nea Smyrni → Moschato

Based on typical Athens traffic patterns, after a few months of data you'll likely see:

- **Thursday 18:00** will have the longest times (peak evening rush)
- **Monday 16:00** should be moderate (early afternoon, before peak)
- **Friday 17:00** variable — depends on whether people leave work early
- **Summer months** (Jul-Aug) significantly faster due to holidays
- **September** will show a spike as schools resume
- **December** will have holiday shopping traffic patterns
- **Routes via Hamosternas/Thivon** may be faster than Pireos during peak hours

## Tips

1. **Be patient**: You need 4+ weeks of data before patterns become reliable
2. **Check consistency**: A slightly slower but consistent route is often better than a fast-but-unpredictable one
3. **Seasonal adjustment**: Re-check recommendations when seasons change (Sept, Jun)
4. **Manual override**: Force a collection anytime with `php collector.php --force`
