# Google Maps Directions, Traffic & Distance Matrix (`rastriq/google-maps-directions-traffic`) Actor

Gets Google Maps routes, travel times, live and predicted traffic, distance matrices, traffic time series and transit itineraries with fares for driving, transit, walking and cycling. No API key.

- **URL**: https://apify.com/rastriq/google-maps-directions-traffic.md
- **Developed by:** [Rastriq — Structured data from the world](https://apify.com/rastriq) (community)
- **Categories:** Travel, Automation, Developer tools
- **Stats:** 3 total users, 2 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 directions results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Google Maps Directions, Traffic & Distance Matrix

Get **routes, travel times, live and predicted traffic, distance matrices, traffic time series, public-transit timetables, lines and fares** from Google Maps — for **driving, transit, walking and cycling**. No API key, no browser, no Google Cloud billing.

**What makes it different**

- 🧮 **Distance matrix built in** — paste N origins and M destinations, get every pair plus a ready-to-use matrix (seconds / meters) in the `OUTPUT` record.
- 📈 **Traffic profile (time series)** — the same route measured every N minutes across one or more days: find rush hours, the best time to leave, delivery windows.
- 🚦 **Rich traffic data** — duration in traffic, duration without traffic, Google's *typical range* ("35 min to 1 hr"), traffic level, delay in seconds, and a speed profile along the route.
- 🚆 **Full transit itineraries** — departure/arrival times with time zones, lines with colours, headsigns, boarding/alighting stops with coordinates, number of stops, operators, **fares**, transfers, walking distance and **service alerts**.
- 🔗 **Many inputs in one run** — route lists, origin × destination matrices and pasted Google Maps links, combined with several travel modes and time slots.
- ⚡ **Fast and cheap** — pure HTTP; hundreds of routes per minute on 512 MB.

### Use cases

- **Logistics & last mile:** travel-time matrices between depots and customers, delivery-window planning by hour.
- **Real estate & retail location:** commute times and catchment areas by car and public transport.
- **Mobility & urban research:** congestion profiles of corridors, transit vs car comparisons, time series for dashboards.
- **Travel & HR tools:** door-to-door itineraries with timetables and fares, employee commute studies.
- **AI agents:** structured directions for any trip in one call.

### Input

In Apify Console everything is point-and-click: route rows with an origin and destination field, dropdowns for travel mode and time, a calendar for dates, and multi-select chips for weekdays and transit vehicles.

**Routes** — one row per trip (origin, destination, optional mode, stops in between and a label). Places can be addresses, place names or `lat,lng`.

**📋 Bulk routes** — paste hundreds of routes at once, one per line: `Origin -> Destination`, `Origin | Destination`, or two columns copied straight from Excel / Google Sheets.

**🕒 When** — *Leave now*, *Depart at* or *Arrive by*, with a calendar **Date** and a **Time** dropdown (local time at the origin). Dates can also be relative — `1 day` means tomorrow — so scheduled runs always look ahead.

Via API:

```json
{
  "routes": [
    { "origin": "Madrid, Spain", "destination": "Barcelona, Spain", "label": "Road trip" },
    { "origin": "Berlin Hauptbahnhof", "destination": "München Hbf", "travelMode": "transit" },
    { "origin": "Madrid, Spain", "destination": "Barcelona, Spain", "waypoints": ["Zaragoza, Spain"] }
  ],
  "routesBulk": ["40.4168,-3.7038 -> 41.3874,2.1686"],
  "timeMode": "depart_at",
  "travelDate": "1 day",
  "travelTime": "08:30"
}
```

API users can also set `departureTime` / `arrivalTime` (`YYYY-MM-DDTHH:MM`) and `avoidTolls` / `avoidHighways` / `avoidFerries` on individual routes.

#### Distance matrix

```json
{
  "origins": ["Getafe, Spain", "Alcobendas, Spain"],
  "destinations": ["Plaza de Castilla, Madrid", "Atocha, Madrid", "Madrid-Barajas Airport T4"],
  "travelModes": ["driving", "transit"]
}
```

2 × 3 pairs × 2 modes = 12 results.

#### Traffic profile (time series)

Pick a date range in the calendar, optionally keep only some weekdays, and choose the hours and the interval:

```json
{
  "routes": [{ "origin": "Getafe, Spain", "destination": "Plaza de Castilla, Madrid" }],
  "trafficProfileStartDate": "2026-11-02",
  "trafficProfileEndDate": "2026-11-29",
  "trafficProfileWeekdays": ["mon", "fri"],
  "trafficProfileStartTime": "06:00",
  "trafficProfileEndTime": "22:00",
  "trafficProfileInterval": "30"
}
```

8 days (4 Mondays + 4 Fridays) × 33 departures = 264 results. Use future dates for Google's predicted traffic; relative dates (`1 day` … `7 days`) work for scheduled weekly runs.

#### Other options

| Field | Description |
|---|---|
| `travelModes` | Modes for routes set to *Default* (select several to compare modes). |
| `directionsUrls` | Google Maps directions links — stops and mode are read from the link. |
| `avoidTolls`, `avoidHighways`, `avoidFerries` | Driving avoidances. |
| `transitTypes` | Prefer `bus`, `subway`, `train`, `tram`. |
| `transitRoutePreference` | `best`, `fewer_transfers`, `less_walking`, `wheelchair` (beta). |
| `maxRoutes` | Alternatives kept per request (default 3). |
| `outputFormat` | `request` (one row per request) or `route` (one row per alternative). |
| `includeSteps`, `stepsForAllRoutes`, `includePolyline`, `includeDetailedPolyline`, `includeSpeedProfile`, `includeStreetView` | Control output detail. `includeDetailedPolyline` adds the full-resolution geometry (every curve). |
| `fixAmbiguousPlaces` | On by default: if a bare city name resolves to a business with the same name, retry once with the country added (recorded in `geocodeCorrections`). |
| `language`, `countryCode` | Output language (40+) and region bias for ambiguous place names. |

### Output

One item per request. The best route is flattened into columns (easy CSV/Excel export) and every alternative is kept in `routes`.

```json
{
  "origin": "Getafe, Spain",
  "destination": "Plaza de Castilla, Madrid",
  "travelMode": "driving",
  "timeMode": "depart_at",
  "requestedTime": "2026-10-14T08:30",
  "status": "OK",
  "via": "A-42 and M-30",
  "distanceMeters": 25770,
  "distanceText": "25.8 km",
  "durationSeconds": 1882,
  "durationInTrafficSeconds": 2700,
  "durationInTrafficText": "45 min",
  "typicalMinSeconds": 2100,
  "typicalMaxSeconds": 3600,
  "typicalRangeText": "35 min to 1 hr",
  "trafficLevel": "heavy",
  "trafficDelaySeconds": 1001,
  "arrivalTime": "2026-10-14T09:30:00+02:00",
  "hasTolls": false,
  "resolvedOrigin": { "name": "Getafe, Madrid, Spain", "placeId": "ChIJAYK7HpogQg0R_ELkt5D6wyA", "location": { "lat": 40.3082504, "lng": -3.7323934 } },
  "routeCount": 3,
  "routes": [
    {
      "rank": 1,
      "summary": "A-42 and M-30",
      "distance": { "meters": 25770, "km": 25.77, "miles": 16.013, "text": "25.8 km" },
      "duration": { "seconds": 1882, "minutes": 31.4, "text": "31 min" },
      "description": "Fastest route now due to traffic conditions",
      "traffic": {
        "durationInTraffic": { "seconds": 2700, "text": "45 min" },
        "durationWithoutTraffic": { "seconds": 1699, "text": "28 min" },
        "typicalDurationRange": { "minSeconds": 2100, "maxSeconds": 3600, "text": "35 min to 1 hr" },
        "trafficLevel": "heavy",
        "arriveAround": { "localIso": "2026-10-14T09:30:00+02:00", "timezone": "Europe/Madrid" },
        "speedSummary": { "averageSpeedKmh": 37.5, "distanceMetersBySpeed": { "under20kmh": 2898, "20to50kmh": 12021, "50to80kmh": 7485, "over80kmh": 3358 } }
      },
      "steps": [
        { "instruction": "Turn right onto C. Leganés", "maneuver": "turn-right", "distance": { "meters": 73, "text": "73 m" }, "duration": { "seconds": 20, "text": "20 sec" }, "startLocation": { "lat": 40.3072, "lng": -3.7338 } }
      ],
      "overviewPolyline": "mm~uFdsoU_c@~u@|c@p}B..."
    }
  ],
  "googleMapsUrl": "https://www.google.com/maps/dir/Getafe,%20Spain/Plaza%20de%20Castilla,%20Madrid/data=!4m2!4m1!3e0"
}
```

Transit routes add `departureTime`, `arrivalTime`, `fare` (`amount`, `currency`), `transitLines` (vehicle, line, agency, from/to stop, number of stops), `numTransfers`, `walkingDistanceMeters`, `agencies` and, in `steps`, line colours, headsigns, stop coordinates, timetable times and service alerts.

`status` is `OK`, `NO_ROUTE` (Google has no route for that mode/time — e.g. no ferry at that hour) or `ERROR`. You are charged only for `OK` results.

#### Place names: get the right place every time

Google resolves free text, so **bare names can be ambiguous** ("Springfield", "Palma", "Barcelona"). Every result includes `resolvedOrigin` / `resolvedDestination` (name, Google `placeId`, coordinates) so you can verify what was used, and `geocodeWarnings` flags doubtful matches. For best results use *city + country*, full addresses, or `lat,lng` coordinates.

#### Field notes

- **`duration`** is Google's base route duration; **`durationInTraffic`** is the traffic-aware estimate for the requested time; **`typicalDurationRange`** is the range Google shows as "typically …"; **`arriveAround`** is Google's conservative ETA (it uses the upper part of the range).
- Times you send are **local wall-clock times at the origin**; returned times include the time zone and UTC offset.
- The polyline is Google's overview for driving and a maneuver-level path for the other modes.

### Pricing

Pay per event — you only pay for successful results:

| Event | Price |
|---|---|
| Directions result (status `OK`) | **$2.00 per 1,000** ($0.002 each) |
| Actor start | $0.003 per run (one event per GB of memory; default 512 MB = one event) |

- One directions request = one result, whatever the number of alternatives, steps or transit details returned.
- Matrix pairs, extra travel modes and traffic-profile time slots each count as one result.
- `NO_ROUTE` and `ERROR` results are **free**; the automatic retry for ambiguous place names is not charged twice.
- Set *Max cost per run* in the run options to cap spending — the actor stops cleanly when it is reached.

**Examples:** one route = $0.005 · 10 × 10 driving matrix = $0.203 · 20 routes every 30 min from 06:00 to 22:00 on 5 days (3,300 results) = $6.60.

### FAQ

**Do I need a Google API key?** No.

**How fresh is traffic?** "Leave now" uses Google's live traffic; future departures use Google's traffic prediction for that day and time.

**Why does a route return `NO_ROUTE`?** Google has no itinerary for that mode or time (e.g. transit at night, a ferry crossing outside its timetable, intercontinental driving).

**Is this legal?** The actor reads publicly available route information. You are responsible for using the data in line with applicable laws and the terms of the sources.

# Actor input Schema

## `routes` (type: `array`):

Add one row per trip. <b>Origin</b> and <b>Destination</b> accept addresses, place names or <code>lat,lng</code> coordinates — add the city and country for best results (e.g. <i>Gran Vía 1, Madrid, Spain</i>).<br>Have many routes? Paste them in <b>📋 Bulk routes</b> below.

## `travelModes` (type: `array`):

Mode(s) used for routes set to <i>Default</i>, for the distance matrix and for links without a mode. Pick several to compare car vs public transport side by side — each mode is one result.

## `timeMode` (type: `string`):

<b>Leave now</b>: live traffic and next departures.<br><b>Depart at</b> / <b>Arrive by</b>: pick a date and time below — ideal for predicted rush-hour traffic or timetables.

## `travelDate` (type: `string`):

Used with <i>Depart at</i> / <i>Arrive by</i>. Pick a day in the calendar, or use a relative value like <code>1 day</code> (= tomorrow) — handy for scheduled runs.

## `travelTime` (type: `string`):

Local time at the origin (24h). Pick from the list or type any time, e.g. <code>08:45</code>.

## `routesBulk` (type: `array`):

One route per line: <code>Origin -> Destination</code>. Also accepted: two columns pasted from a spreadsheet (tab-separated), <code>Origin | Destination</code> or <code>Origin; Destination</code>. Add stops in between with more arrows: <code>Madrid -> Zaragoza -> Barcelona</code>.

## `origins` (type: `array`):

One place per line (addresses, place names or <code>lat,lng</code>). 10 origins × 20 destinations = 200 results.

## `destinations` (type: `array`):

One place per line.

## `directionsUrls` (type: `array`):

Paste Google Maps directions links, e.g. <code>https://www.google.com/maps/dir/Bilbao/San+Sebastián/...</code> or <code>https://www.google.com/maps/dir/?api=1\&origin=...\&destination=...</code>. Stops and travel mode are read from the link.

## `trafficProfileStartDate` (type: `string`):

First day. Pick it in the calendar or use a relative value like <code>1 day</code> (tomorrow) for scheduled runs. Use future dates for Google's predicted traffic.

## `trafficProfileEndDate` (type: `string`):

Last day (optional — defaults to <i>From date</i>). Up to 93 days.

## `trafficProfileWeekdays` (type: `array`):

Optional: keep only these days of the week within the date range (e.g. Monday + Friday). Empty = every day.

## `trafficProfileStartTime` (type: `string`):

First departure of each day.

## `trafficProfileEndTime` (type: `string`):

Last departure of each day.

## `trafficProfileInterval` (type: `string`):

Time between departures. Example: 06:00–22:00 every hour = 17 results per route and day.

## `avoidTolls` (type: `boolean`):

Driving: prefer routes without toll roads.

## `avoidHighways` (type: `boolean`):

Driving: prefer routes without motorways.

## `avoidFerries` (type: `boolean`):

Driving: prefer routes without ferries.

## `transitTypes` (type: `array`):

Transit: prefer these vehicle types (Google still falls back to others if there is no alternative). Leave empty for all.

## `transitRoutePreference` (type: `string`):

Transit: how Google should rank itineraries.

## `maxRoutes` (type: `integer`):

Maximum number of route alternatives kept per request (Google returns up to ~6 for transit, ~3 for driving, 1 for multi-stop trips).

## `outputFormat` (type: `string`):

<b>One row per request</b>: best route flattened into columns + all alternatives in <code>routes</code>. <b>One row per route</b>: every alternative is its own row (handy for spreadsheets).

## `includeSteps` (type: `boolean`):

Instructions, maneuvers, distances, durations and coordinates for each step; for transit: line, colour, headsign, stops, times, agency and service alerts. Included for the best route only unless 'Steps for all routes' is on.

## `stepsForAllRoutes` (type: `boolean`):

Also include steps for alternative routes (bigger output).

## `includePolyline` (type: `boolean`):

Encoded polyline (Google format) to draw each route on a map.

## `includeDetailedPolyline` (type: `boolean`):

Adds <code>detailedPolyline</code>: the full-resolution route geometry (every curve, points ≥5 m apart) for map matching, geofencing or distance-along-route analysis. Makes responses larger and runs slower — leave off unless you need it.

## `includeSpeedProfile` (type: `boolean`):

Driving: segment-by-segment traffic-aware speeds along the route (fromMeters, toMeters, seconds, speedKmh). A summary by speed band is always included.

## `includeStreetView` (type: `boolean`):

Add a Street View thumbnail URL to each maneuver.

## `language` (type: `string`):

Language of instructions, road names and text fields.

## `countryCode` (type: `string`):

Optional: country used to interpret ambiguous place names. Pick one or type any 2-letter code. Adding the country to each address is still the most reliable.

## `fixAmbiguousPlaces` (type: `boolean`):

Google sometimes resolves a bare city name to a business with that name (e.g. <code>Barcelona</code> → a restaurant in Barcelona). When detected, the request is retried once with the country added (<code>Barcelona, Spain</code>) and the change is recorded in <code>geocodeCorrections</code>. Not charged twice.

## `maxResults` (type: `integer`):

Safety cap on the number of directions requests (after expanding matrix, modes and traffic slots). 0 = no cap.

## `maxConcurrency` (type: `integer`):

Parallel requests. The actor backs off automatically if Google slows down.

## `proxyConfiguration` (type: `object`):

Leave on <b>No proxy</b> (recommended): the actor connects directly — fastest and cleanest results — and <b>switches to Apify Proxy automatically</b> if Google starts blocking. Select a proxy only if you need requests from a specific country/IP type.

## `dateTime` (type: `string`):

Legacy: YYYY-MM-DDTHH:MM. Use Date + Time instead.

## `trafficProfileDates` (type: `array`):

Legacy list of YYYY-MM-DD dates. Use From/To date instead.

## `trafficProfileIntervalMinutes` (type: `integer`):

Legacy. Use 'Every' instead.

## `debug` (type: `boolean`):

Save raw Google responses of NO_ROUTE results to the key-value store.

## Actor input object example

```json
{
  "routes": [
    {
      "origin": "Madrid, Spain",
      "destination": "Barcelona, Spain",
      "travelMode": "default",
      "label": "Road trip"
    },
    {
      "origin": "Berlin Hauptbahnhof",
      "destination": "München Hbf",
      "travelMode": "transit"
    }
  ],
  "travelModes": [
    "driving"
  ],
  "timeMode": "now",
  "travelTime": "08:30",
  "trafficProfileStartTime": "06:00",
  "trafficProfileEndTime": "22:00",
  "trafficProfileInterval": "60",
  "avoidTolls": false,
  "avoidHighways": false,
  "avoidFerries": false,
  "transitRoutePreference": "best",
  "maxRoutes": 3,
  "outputFormat": "request",
  "includeSteps": true,
  "stepsForAllRoutes": false,
  "includePolyline": true,
  "includeDetailedPolyline": false,
  "includeSpeedProfile": false,
  "includeStreetView": false,
  "language": "en",
  "fixAmbiguousPlaces": true,
  "maxResults": 0,
  "maxConcurrency": 10,
  "proxyConfiguration": {
    "useApifyProxy": false
  },
  "debug": false
}
```

# Actor output Schema

## `results` (type: `string`):

All results: best route flattened into columns plus every alternative in 'routes'.

## `overview` (type: `string`):

Key columns: distance, duration, traffic, times and fares.

## `traffic` (type: `string`):

Traffic-aware durations, typical ranges and delays per requested time.

## `matrix` (type: `string`):

One row per origin × destination pair.

## `summary` (type: `string`):

JSON summary: counts, HTTP stats, warnings and matrix grids (seconds / meters).

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "routes": [
        {
            "origin": "Madrid, Spain",
            "destination": "Barcelona, Spain",
            "travelMode": "default",
            "label": "Road trip"
        },
        {
            "origin": "Berlin Hauptbahnhof",
            "destination": "München Hbf",
            "travelMode": "transit"
        }
    ],
    "travelTime": "08:30",
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("rastriq/google-maps-directions-traffic").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "routes": [
        {
            "origin": "Madrid, Spain",
            "destination": "Barcelona, Spain",
            "travelMode": "default",
            "label": "Road trip",
        },
        {
            "origin": "Berlin Hauptbahnhof",
            "destination": "München Hbf",
            "travelMode": "transit",
        },
    ],
    "travelTime": "08:30",
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("rastriq/google-maps-directions-traffic").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "routes": [
    {
      "origin": "Madrid, Spain",
      "destination": "Barcelona, Spain",
      "travelMode": "default",
      "label": "Road trip"
    },
    {
      "origin": "Berlin Hauptbahnhof",
      "destination": "München Hbf",
      "travelMode": "transit"
    }
  ],
  "travelTime": "08:30",
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call rastriq/google-maps-directions-traffic --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rastriq/google-maps-directions-traffic"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/XWjuBJ8VjJ9txdu0G/builds/nfHYEIP7uMBLsUbqx/openapi.json
