# Google Maps Directions and Routes API (`automation-lab/google-maps-directions-routes-api`) Actor

Extract Google Maps route alternatives with multi-stop legs, navigation steps, distance, duration, traffic estimates, and encoded paths.

- **URL**: https://apify.com/automation-lab/google-maps-directions-routes-api.md
- **Developed by:** [Stas Persiianenko](https://apify.com/automation-lab) (community)
- **Categories:** Travel, Developer tools, Integrations
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.36 / 1,000 route extracteds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Google Maps Directions and Routes API

Calculate **Google Maps directions** and export route alternatives as structured JSON, CSV, Excel, or API data.

Submit one origin-destination pair or a batch.

Each saved row can include:

- route alternatives ranked by Google Maps;
- ordered waypoint legs;
- turn-by-turn navigation steps;
- distance in text and meters;
- duration in text and seconds;
- traffic-aware ETA ranges when Google exposes them;
- warnings such as toll advisories;
- encoded step-boundary paths;
- source URLs and fetch timestamps.

No Google Maps Platform API key is required.

This Actor reads the public Google Maps directions flow. It is not the official Google Routes API and does not promise contractual Google API behavior.

### What does this Google Maps directions Actor do?

The Actor turns route requests into automation-ready route records.

For each request, it opens the public Google Maps directions surface, retrieves the structured route preview, normalizes the alternatives, and stores one dataset row per route alternative.

A route row contains nested legs.

Each leg contains ordered navigation steps.

This structure works for simple point-to-point trips and multi-stop routes with up to eight waypoints.

Supported travel modes are:

- driving;
- walking;
- bicycling;
- transit.

Traffic estimates are included only when the source exposes them, usually for driving routes.

### Who is it for?

#### Logistics and dispatch teams

Calculate lane distance, ETA, route options, waypoint legs, and traffic ranges before assigning work.

#### Field service businesses

Estimate travel from depots to appointments and enrich job records with machine-readable distance and duration.

#### Travel and mobility analysts

Compare public route alternatives and preserve route labels, warnings, steps, and timestamps for analysis.

#### Developers and AI agents

Use a JSON-first directions tool without managing a Google Maps Platform key.

#### Data and operations teams

Schedule recurring route requests and send datasets to spreadsheets, databases, dashboards, Make, Zapier, or n8n.

### Why use this route API?

Manual route checks do not scale across many origin-destination pairs.

This Actor provides:

- batch input with per-row mode overrides;
- consistent numeric units;
- nested multi-stop legs;
- plain-text instructions;
- traffic context when present;
- encoded paths for compact geometry transfer;
- conservative direct HTTP execution with 256 MB memory;
- explicit failure when Google returns a challenge or unsupported payload instead of false empty success.

The Actor does not launch a browser or enable a paid proxy fallback during normal runs.

### What data can you extract?

| Field | Meaning |
| --- | --- |
| `origin` | Origin supplied by the user |
| `destination` | Destination supplied by the user |
| `waypoints` | Ordered intermediate stops |
| `travelMode` | Driving, walking, bicycling, or transit |
| `avoid` | Requested toll, highway, or ferry avoidance |
| `routeIndex` | One-based alternative rank |
| `routeLabel` | Road corridor or transit service label |
| `distanceMeters` | Total distance in meters |
| `distanceText` | Localized distance text |
| `durationSeconds` | Total duration in seconds |
| `durationText` | Localized duration text |
| `trafficEstimate` | Expected, best-case, and range values when available |
| `warnings` | Route advisories such as toll warnings |
| `legs` | Ordered waypoint-split legs |
| `legs[].steps` | Navigation instructions and maneuver details |
| `encodedPath` | Encoded polyline from step-boundary coordinates |
| `pathPointCount` | Number of coordinates encoded in the path |
| `pathPrecision` | Always `step-boundary` |
| `mapsUrl` | Public Google Maps directions URL |
| `previewUrl` | Structured preview endpoint used by the run |
| `fetchedAt` | ISO 8601 fetch timestamp |

Nested steps include instruction, maneuver, distance, duration, start coordinate, and end coordinate when available.

### How to calculate a route

1. Open the Actor input page.
2. Enter `origin` and `destination`.
3. Add optional `waypoints` in visit order.
4. Select a travel `mode`.
5. Choose road features to `avoid` where relevant.
6. Set language and country bias.
7. Choose up to three route alternatives.
8. Run the Actor.
9. Open the default dataset.
10. Download JSON, CSV, Excel, XML, or RSS output.

The prefilled Manhattan walking request is ready to run.

### Input parameters

#### `origin`

A place name, full address, landmark, or `latitude,longitude` pair for a single request.

Example: `Empire State Building, New York, NY`.

#### `destination`

The final place for a single request.

Example: `Times Square, New York, NY`.

#### `waypoints`

Zero to eight intermediate stops.

Google Maps visits them in the supplied order.

#### `mode`

One of `driving`, `walking`, `bicycling`, or `transit`.

#### `avoid`

Any combination of `tolls`, `highways`, and `ferries`.

Availability depends on travel mode and source behavior.

#### `locale` and `country`

`locale` controls instruction language.

`country` biases ambiguous place resolution and localized units.

#### `maxRouteAlternatives`

Save one to three alternatives per request.

Google Maps may return fewer alternatives than requested.

#### `routes`

Optional batch of up to 50 route objects.

When `routes` is supplied, it replaces the top-level single request.

Each batch row can override mode, waypoints, avoidance, locale, country, and alternative count.

#### `maxItems`

Global cap on saved route alternatives across the run.

#### `requestDelayMs`

Delay between separate requests.

It does not delay alternatives from the same response.

### Single-route input example

```json
{
  "origin": "Empire State Building, New York, NY",
  "destination": "Times Square, New York, NY",
  "mode": "walking",
  "maxRouteAlternatives": 2,
  "maxItems": 2,
  "requestDelayMs": 0
}
```

### Multi-stop driving input example

```json
{
  "origin": "New York, NY",
  "destination": "Washington, DC",
  "waypoints": ["Philadelphia, PA", "Baltimore, MD"],
  "mode": "driving",
  "avoid": ["ferries"],
  "maxRouteAlternatives": 1,
  "maxItems": 1
}
```

This request produces one route with three ordered legs.

### Batch mode example

```json
{
  "routes": [
    {
      "origin": "Union Square, San Francisco, CA",
      "destination": "Ferry Building, San Francisco, CA",
      "mode": "transit",
      "maxRouteAlternatives": 1
    },
    {
      "origin": "Golden Gate Park, San Francisco, CA",
      "destination": "Golden Gate Bridge, San Francisco, CA",
      "mode": "bicycling",
      "maxRouteAlternatives": 1
    }
  ],
  "maxItems": 2,
  "requestDelayMs": 100
}
```

### Output example

The following values reflect a real multi-stop local run; traffic changes over time.

```json
{
  "origin": "New York, NY",
  "destination": "Washington, DC",
  "waypoints": ["Philadelphia, PA", "Baltimore, MD"],
  "travelMode": "driving",
  "routeIndex": 1,
  "routeLabel": "I-95 S",
  "distanceMeters": 375659,
  "distanceText": "233 miles",
  "durationSeconds": 16417,
  "durationText": "4 hr 34 min",
  "trafficEstimate": {
    "durationSeconds": 18248,
    "durationText": "5 hr 4 min",
    "bestCaseSeconds": 14714,
    "bestCaseText": "4 hr 5 min",
    "rangeMinSeconds": 15244,
    "rangeMaxSeconds": 23918,
    "rangeText": "4 hr 14 min to 6 hr 39 min"
  },
  "warnings": ["This route has tolls."],
  "legs": [
    {
      "legIndex": 1,
      "origin": "New York, NY",
      "destination": "Philadelphia, PA",
      "distanceMeters": 152105,
      "durationSeconds": 6214,
      "steps": [
        {
          "stepIndex": 1,
          "instruction": "Head toward Park Row",
          "maneuver": "depart",
          "distanceMeters": 61,
          "durationSeconds": 18
        }
      ]
    }
  ],
  "pathPointCount": 108,
  "pathPrecision": "step-boundary",
  "fetchedAt": "2026-09-01T14:00:00.000Z"
}
```

### Encoded path precision

`encodedPath` uses the standard encoded-polyline algorithm.

The coordinates come from source-provided navigation step boundaries.

This is intentionally labeled `step-boundary` precision.

It is useful for:

- compact route sequence storage;
- lightweight map previews;
- detecting broad path changes;
- joining navigation steps to approximate locations.

It is not a full road-vertex trace and should not be presented as survey-grade geometry.

### Traffic estimate behavior

Driving routes often expose an expected traffic duration, best-case duration, and range.

Traffic fields are omitted when Google Maps does not expose them.

Walking, bicycling, and transit normally return duration without road-traffic ranges.

Traffic values change with request time, road conditions, incidents, locale, and source behavior.

Do not use public estimates as safety-critical navigation instructions.

### How much does it cost to calculate Google Maps routes?

The Actor uses pay-per-event pricing:

- one `start` event per run;
- one `route` event per saved route alternative.

Legs, steps, traffic estimates, warnings, and encoded paths are included in the route event.

They do not create separate charges.

The one-time start event is **$0.005** on every plan.

| Plan tier | Price per saved route alternative |
| --- | ---: |
| Free | $0.0026036 |
| Bronze | $0.002264 |
| Silver | $0.0017659 |
| Gold | $0.0013584 |
| Platinum | $0.0009056 |
| Diamond | $0.00063392 |

For a workload estimate, add the one-time start event to the applicable per-route tier price multiplied by the maximum saved alternatives. For example, a Bronze run with ten saved alternatives is one start event plus ten Bronze route events.

Your Apify plan determines which tier applies, and Apify shows the active event prices before the run starts.

Use `maxItems` and `maxRouteAlternatives` to set a predictable output ceiling.

A request that returns one alternative charges one route event.

A request that returns three alternatives charges three route events.

### Common workflows

#### Delivery lane planning

Submit depot, stop, and destination sequences.

Compare leg distances, durations, traffic ranges, and toll warnings.

#### Field-service enrichment

Batch customer appointments and add travel seconds/meters to operational records.

#### Route alternative comparison

Save up to three alternatives and compare route label, ETA, warnings, and path sequence.

#### Transit and active mobility research

Run transit, walking, and bicycling requests with typed instructions and durations.

#### Scheduled route monitoring

Schedule the same request and compare timestamps, ETA ranges, warnings, and encoded paths over time.

The Actor returns snapshots; it does not calculate changes or send alerts by itself.

### Integrations

Export to Google Sheets for route comparison tables.

Send datasets to Airtable for dispatch records.

Trigger runs from Make, Zapier, or n8n.

Load route alternatives into BigQuery, Snowflake, PostgreSQL, or a data warehouse.

Use webhooks after runs complete.

Feed typed output to an AI agent through Apify MCP.

### JavaScript API example

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

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });

const run = await client.actor(
  'automation-lab/google-maps-directions-routes-api'
).call({
  origin: 'New York, NY',
  destination: 'Washington, DC',
  waypoints: ['Philadelphia, PA'],
  mode: 'driving',
  maxRouteAlternatives: 2
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items);
```

### Python API example

```python
from apify_client import ApifyClient

client = ApifyClient('YOUR_APIFY_TOKEN')

run = client.actor(
    'automation-lab/google-maps-directions-routes-api'
).call(run_input={
    'origin': 'New York, NY',
    'destination': 'Washington, DC',
    'waypoints': ['Philadelphia, PA'],
    'mode': 'driving',
    'maxRouteAlternatives': 2,
})

for item in client.dataset(run['defaultDatasetId']).iterate_items():
    print(item)
```

### cURL API example

```bash
curl -X POST \
  'https://api.apify.com/v2/acts/automation-lab~google-maps-directions-routes-api/runs?token=YOUR_APIFY_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
    "origin": "Empire State Building, New York, NY",
    "destination": "Times Square, New York, NY",
    "mode": "walking",
    "maxRouteAlternatives": 2
  }'
```

Do not commit tokens to source control.

### MCP setup

Claude Code:

```bash
claude mcp add --transport http apify \
  "https://mcp.apify.com?tools=automation-lab/google-maps-directions-routes-api"
```

#### Claude Desktop, Cursor, and VS Code setup

Use the same HTTP server configuration in Claude Desktop, Cursor, or VS Code:

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com?tools=automation-lab/google-maps-directions-routes-api"
    }
  }
}
```

Example prompts:

- "Calculate three walking alternatives from the Empire State Building to Times Square."
- "Return a multi-stop driving route from New York to Washington via Philadelphia and include traffic ranges."
- "Compare transit and bicycling routes for these San Francisco place pairs."
- "Export the legs and navigation steps to a JSON dataset."

### Reliability and retry behavior

The Actor retries transient network errors, HTTP 429, and temporary server failures up to three times.

It does not blindly retry malformed input or stable 4xx responses.

It fails explicitly when:

- origin or destination is missing;
- a mode or avoidance value is unsupported;
- a route contains more than eight waypoints;
- Google returns a challenge or consent page;
- no structured route preview exists;
- the preview payload shape is unsupported;
- no valid route alternatives can be parsed.

A failed request does not become a successful empty dataset.

### Tips for accurate routes

Use complete addresses for ambiguous places.

Add city, state, postal code, or country context.

Use coordinates for operational sites that need precise resolution.

Set the country bias to the route geography.

Set the locale to the language required by downstream users.

Start with one alternative when you need only the primary route.

Review a small sample before scheduling large batches.

### Limitations

Google Maps is dynamic and can change its public payload.

This Actor is not an official Google Maps Platform API client.

It does not use private accounts, saved places, or location history.

It does not expose departure-time or arrival-time controls.

It does not optimize waypoint order.

It visits waypoints in the supplied order.

Encoded paths contain maneuver boundaries, not every road vertex.

Traffic estimates appear only when exposed by Google Maps.

Transit details vary by agency and region.

Source labels and units can differ by locale.

### Legality and responsible use

Use this Actor only for lawful, proportionate workflows.

Respect Google Maps terms, Apify rules, and applicable laws.

Do not overload public services.

Do not use route estimates as the sole basis for emergency, safety-critical, or regulated decisions.

Avoid sending confidential addresses unless your processing basis and data controls permit it.

### Troubleshooting

#### No preview route is available

Check place spelling and route feasibility.

Add city, state, country, or coordinates.

Some origin-destination combinations have no route for the selected mode.

#### Google returned a challenge

Retry later with a small request.

The Actor does not silently switch to a paid proxy or browser route.

#### Fewer alternatives were returned

`maxRouteAlternatives` is a ceiling.

Google Maps can return one, two, or three routes depending on the request.

#### Traffic fields are missing

Traffic ranges are source-dependent and normally apply to driving routes.

Base duration remains available when a valid route is returned.

#### A path looks simplified

This is expected.

Check `pathPrecision` and `pathPointCount`.

The encoded path joins navigation step boundaries.

### FAQ

#### Is a Google API key required?

No.

The Actor uses the public Google Maps directions flow.

#### Does it support waypoints?

Yes, up to eight ordered intermediate stops.

#### Does it return navigation steps?

Yes, route legs contain ordered plain-text steps with maneuver, distance, duration, and coordinates when available.

#### Does it return route alternatives?

Yes, up to three alternatives per request when Google Maps exposes them.

#### Does it include live traffic?

It includes the traffic-aware estimate and range exposed at fetch time when available.

It does not promise real-time or contractual traffic accuracy.

#### Can it optimize stop order?

No.

Waypoints remain in the supplied order.

#### Can it process a batch?

Yes, up to 50 route requests per run and up to 150 saved alternatives.

#### Are legs or steps charged separately?

No.

They are included in each saved route event.

### Related automation-lab Actors

Use other `automation-lab` Google Maps Actors when your primary entity is a place, review, lead, or local-rank observation rather than a route.

Choose this Actor when the buyer job starts with origins, destinations, modes, and waypoints and ends with route alternatives, legs, steps, ETA, and path data.

### Support

If output looks incorrect, include the Apify run ID and a minimal reproducible input.

Share the mode, origin, destination, waypoints, locale, country, and the affected route field.

Do not include API tokens or confidential addresses in public support messages.

# Actor input Schema

## `origin` (type: `string`):

Starting address, place name, or latitude,longitude pair for a single route request.

## `destination` (type: `string`):

Ending address, place name, or latitude,longitude pair for a single route request.

## `waypoints` (type: `array`):

Up to 8 intermediate stops, visited in the supplied order.

## `mode` (type: `string`):

Default travel mode for the single request and batch rows that do not set their own mode.

## `avoid` (type: `array`):

Road features Google Maps should avoid where the selected mode supports them.

## `locale` (type: `string`):

Language code for Google Maps labels and navigation instructions, such as en, de, or fr.

## `country` (type: `string`):

Two-letter country code used to resolve ambiguous place names and localize units.

## `maxRouteAlternatives` (type: `integer`):

Maximum number of Google Maps route alternatives to save for each request. Google Maps may return fewer.

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

Optional batch of up to 50 origin-destination requests. When supplied, it replaces the top-level single route.

## `maxItems` (type: `integer`):

Global cap on route-alternative records saved across all requests.

## `requestDelayMs` (type: `integer`):

Conservative delay between separate route requests. No delay is added between alternatives in one response.

## Actor input object example

```json
{
  "origin": "Empire State Building, New York, NY",
  "destination": "Times Square, New York, NY",
  "waypoints": [],
  "mode": "driving",
  "avoid": [],
  "locale": "en",
  "country": "us",
  "maxRouteAlternatives": 3,
  "maxItems": 20,
  "requestDelayMs": 500
}
```

# Actor output Schema

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

Open the default dataset in the route-alternatives view.

# 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 = {
    "origin": "Empire State Building, New York, NY",
    "destination": "Times Square, New York, NY"
};

// Run the Actor and wait for it to finish
const run = await client.actor("automation-lab/google-maps-directions-routes-api").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 = {
    "origin": "Empire State Building, New York, NY",
    "destination": "Times Square, New York, NY",
}

# Run the Actor and wait for it to finish
run = client.actor("automation-lab/google-maps-directions-routes-api").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 '{
  "origin": "Empire State Building, New York, NY",
  "destination": "Times Square, New York, NY"
}' |
apify call automation-lab/google-maps-directions-routes-api --silent --output-dataset

```

## MCP server setup

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

```

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/GjNYLuKB3xiBpFB4w/builds/srCdfV9hSOdPsxSDF/openapi.json
