# Google Maps Directions & Route Report API (`khadinakbar/google-maps-directions-api`) Actor

Get structured Google Maps route reports, with distance, duration, alternatives, optional steps and provenance. Use the included route source or your own Google Routes key.

- **URL**: https://apify.com/khadinakbar/google-maps-directions-api.md
- **Developed by:** [Khadin Akbar](https://apify.com/khadinakbar) (community)
- **Categories:** Travel, Developer tools, MCP servers
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $70.00 / 1,000 route reports

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

### What is Google Maps Directions API?

Get a bounded, agent-friendly Google Maps route report between two known locations. It returns normalized dataset records with distance, duration, alternatives, route links, provider provenance, and optional turn steps for logistics planners, field-service teams, travel workflows, and AI agents. The default provider is a managed Google Maps directions service funded by the Actor owner, so you need no map credentials of your own. A direct Google Routes BYOK mode remains available for Google Place IDs, up to ten ordered stops, traffic-aware routing, and encoded route polylines.

Use this Actor for route research, field-service planning, travel workflows, and AI agents that need distance, duration, alternatives, a Google Maps link, and optional turn steps. Fleet routing, navigation, toll pricing, and place discovery work well as dedicated follow-on workflow stages.

### Best fit

Choose the default managed provider for a known address or coordinate pair when you want real Google Maps directions without supplying a customer key. It supports driving, walking, cycling, transit, alternatives, route preferences, localized text, and bounded turn steps.

Choose `GOOGLE_ROUTES_BYOK` when you own a restricted Google Maps Routes API key and need Google Place IDs, ordered intermediate stops, traffic-aware preferences, `staticDurationSeconds`, or an encoded polyline. The direct key is a secret input and is never written to the dataset, `OUTPUT`, `RUN_SUMMARY`, or logs.

### Focused standalone workflow

This Actor works as a focused standalone workflow for one known origin-destination pair. A field-service coordinator starts with the scheduled visit address, then requests one driving route, compares its duration with the appointment window, and passes the route link plus provenance into a dispatch record.

### Quick start

This default request uses the included managed provider. No customer credential is required.

```json
{
  "origin": "Times Square, New York, NY",
  "destination": "Central Park, New York, NY",
  "travelMode": "DRIVE",
  "maxRouteOptions": 1
}
```

For direct Google Routes features, set `routeProvider` to `GOOGLE_ROUTES_BYOK` and add a restricted Routes API key:

```json
{
  "routeProvider": "GOOGLE_ROUTES_BYOK",
  "googleMapsApiKey": "YOUR_RESTRICTED_GOOGLE_MAPS_ROUTES_KEY",
  "origin": "placeId:ChIJmQJIxlVYwokRLgeuocVOGgQ",
  "destination": "placeId:ChIJ4zGFAZpYwokRGUGph3Mf37k",
  "intermediates": ["Grand Central Terminal, New York, NY"],
  "travelMode": "DRIVE",
  "routingPreference": "TRAFFIC_AWARE",
  "includeSteps": true
}
```

### Input reference

| Field | What it controls |
| --- | --- |
| `routeProvider` | The default option uses the included managed provider. `GOOGLE_ROUTES_BYOK` makes a direct Google Routes request. |
| `origin`, `destination` | Required addresses or `latitude,longitude` pairs. `placeId:` values work in direct Google Routes mode. |
| `googleMapsApiKey` | Optional secret required only for direct Google Routes mode. |
| `intermediates` | Up to ten ordered stops in direct Google Routes mode. |
| `travelMode` | `DRIVE`, `WALK`, `BICYCLE`, or `TRANSIT`. |
| `routingPreference` | Google Routes driving-traffic option; keep `TRAFFIC_UNAWARE` for the managed provider. |
| `computeAlternativeRoutes`, `maxRouteOptions` | Bound the output to one through three route choices from a single provider request. |
| `avoidTolls`, `avoidHighways` | Route-selection preferences with provider-dependent results; toll-price estimates remain outside this contract. |
| `languageCode`, `units` | Two-letter instruction language and metric/imperial display preference. |
| `includeSteps`, `maxStepsPerRoute` | Optional bounded turn instructions, off by default for compact agent output. |

### Output: What you receive

One dataset row represents one route option. One completed provider request is charged once even when it returns up to three retained alternatives.

```json
{
  "routeIndex": 0,
  "routeLabels": ["DEFAULT_ROUTE"],
  "origin": "Times Square, New York, NY",
  "destination": "Central Park, New York, NY",
  "travelMode": "DRIVE",
  "distanceMeters": 4200,
  "durationSeconds": 840,
  "staticDurationSeconds": null,
  "encodedPolyline": null,
  "googleMapsUrl": "https://www.google.com/maps/dir/...",
  "legs": [{ "legIndex": 0, "distanceMeters": 4200, "durationSeconds": 840, "steps": [] }],
  "warnings": ["Google Maps directions were retrieved through the managed provider; encoded polyline geometry is not supplied by this provider."]
}
```

`distanceMeters` and `durationSeconds` are normalized numeric fields. `encodedPolyline` and `staticDurationSeconds` are populated only by the direct Google Routes BYOK provider; they are explicitly `null` for managed-provider records rather than guessed.

### Terminal outcomes

Every run writes compact `OUTPUT` and detailed `RUN_SUMMARY` records.

| Outcome | Meaning |
| --- | --- |
| `COMPLETE` | The selected provider returned route options and every retained option was persisted. |
| `PARTIAL` | At least one usable option persisted but another could not be safely written. |
| `VALID_EMPTY` | The provider accepted a valid request but returned no route option. |
| `INVALID_INPUT` | The submitted locations, provider mode, secret, or incompatible option can be corrected. |
| `UPSTREAM_FAILED` | A valid request could not be completed by its selected provider and no useful route was persisted. |

### Pricing and cost controls

Pay per event pricing charges one `route-report` event for each completed provider request, plus the standard Actor-start event, with Apify platform usage included. One event can persist one to three route records. The live Pricing tab shows the current event prices.

Direct `GOOGLE_ROUTES_BYOK` requests use the same Apify event and are separately billed by Google to the caller's Cloud project. Check the live Pricing tab and your provider account before high-volume production workflows. Set `maxTotalChargeUsd` for Apify and a provider-side quota/budget.

#### Free Apify plan

Runs started from a free Apify plan return up to 25 results per run, with every input mode and output field available. Paid Apify plans have no per-run limit, so your usual result settings apply. Runs that use your own Google Maps Routes API key are not limited.

### Run through the Apify API

```bash
curl "https://api.apify.com/v2/acts/khadinakbar~google-maps-directions-api/runs?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "origin": "Times Square, New York, NY",
    "destination": "Central Park, New York, NY",
    "travelMode": "DRIVE",
    "maxRouteOptions": 1
  }'
```

Read the default dataset after processing, then inspect `OUTPUT` for the terminal outcome and `RUN_SUMMARY` for provider, counts, cost events, and safe diagnostics.

### API and MCP use

Run this regular Actor through the standard Apify API or hosted Apify MCP integration, then read the default dataset for route options and `OUTPUT` for terminal state. For an agent workflow, ask for one bounded route, preserve `provider`, `source`, and `checkedAt` in downstream decisions, and inspect `OUTPUT.outcome` before acting on an empty dataset.

> Compute a driving route from Times Square, New York to Central Park, return one route with distance and duration, include no turn steps, and preserve the provider provenance.

### Best results

- Use the default managed provider for addresses and coordinates without a customer credential.
- Use direct Google Routes BYOK for Place IDs, ordered stops, traffic preferences, or encoded geometry.
- Start with one route option and no steps; enable additional data only when the downstream decision needs it.
- Treat directions as planning information, not real-time navigation or a promise about current road conditions.

### Builder's note

I designed the two provider contracts to be explicit. The managed provider returns Google Maps directions with owner-managed credentials and normalized route fields, while direct Google Routes preserves direct-only features. Every record identifies its actual provider and source, and explicit nulls describe fields outside the selected provider's response shape.

### Responsible use

Use route data in workflows authorized by the selected provider's terms and applicable law. When using direct Google Routes, follow Google Maps Platform attribution, display, retention, and use restrictions. This Actor supports route research and planning workflows rather than real-time navigation, autonomous control, or transportation safety decisions.

# Changelog

This Actor's version history is a separate document: https://apify.com/khadinakbar/google-maps-directions-api/changelog.md

# Actor input Schema

## `routeProvider` (type: `string`):

Select the route provider used for this request. The default managed option uses the Actor owner's managed Google Maps directions account, so no customer map key is needed. `GOOGLE_ROUTES_BYOK` calls Google Routes API directly with your secret Google key and unlocks Place IDs, ordered stops, and traffic preferences. This is not a free-form provider name. Free Apify plan runs return up to 25 results per run.

## `googleMapsApiKey` (type: `string`):

Secret key used only when Route provider is `GOOGLE_ROUTES_BYOK`. Paste a restricted, billing-enabled server key such as `AIza...`; it is sent only to Google and never written to the dataset, output records, or logs. Leave it empty for the included managed Google Maps provider. This is not an Apify token.

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

Starting point for one route request. Use a street address such as `Times Square, New York, NY`, or coordinates such as `40.7580,-73.9855`; `placeId:ChIJ...` is supported only by Google Routes BYOK. Plain text is treated as an address, not a place-search query. This field is required.

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

Ending point for one route request. Use an address or latitude-longitude pair, for example `Central Park, New York, NY`; `placeId:` values require Google Routes BYOK. Submit one origin-destination pair so route options stay bounded and predictable. This field is not a Google Maps directions URL.

## `intermediates` (type: `array`):

Optional ordered stops between Origin and Destination for Google Routes BYOK. Use the same address, coordinate, or `placeId:` formats; the maximum is ten and the Actor does not optimize the order. managed search Google Maps accepts only one start and one end point, so leave this empty with the default provider. This is not a fleet-route optimizer.

## `travelMode` (type: `string`):

Transport mode for the requested route. Choose `DRIVE`, `WALK`, `BICYCLE`, or `TRANSIT`; `DRIVE` is the default. Provider coverage varies by location and Google may return no route for a valid pair. This is not a free-form vehicle name.

## `routingPreference` (type: `string`):

Controls traffic-aware timing when using Google Routes BYOK for driving. `TRAFFIC_UNAWARE` is the default; the two traffic-aware choices require Google Routes BYOK and can change the Google SKU charged to your project. managed search Google Maps has no equivalent selector. This setting is not an ETA guarantee.

## `computeAlternativeRoutes` (type: `boolean`):

Allow the selected provider to return available alternatives in addition to its default route. The Actor still respects Maximum route options, so response size and event pricing remain bounded. Providers may return fewer options than requested. This switch does not create separate provider calls.

## `maxRouteOptions` (type: `integer`):

Maximum route options written from one completed provider request. Choose one through three; the default route is first and the default value is one. This bound does not force a provider to invent alternatives. It is not a number of requests.

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

Ask the provider to avoid toll roads when a reasonable route exists. The default is false and a true value is a route preference rather than a guarantee. Toll price estimates remain outside this contract. This option does not refund real-world tolls.

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

Ask the provider to avoid highways when feasible. The default is false and the resulting route can be longer. This changes route selection only and does not guarantee local-road-only travel. It is not a manual driving instruction.

## `languageCode` (type: `string`):

Two-letter response language code such as `en`, `es`, or `fr`. The default is `en`; a provider can fall back when a localization is unavailable. This changes instruction text, not the origin or destination country. It is not a locale display name.

## `units` (type: `string`):

Select `METRIC` or `IMPERIAL` for provider-formatted distance values. Normalized `distanceMeters` remains meters in every dataset item. The default is `METRIC` and it does not alter route geometry. This is not a currency selector.

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

Include bounded plain-text turn steps in route legs. The default is false to keep agent responses compact; turn it on for workflows that need maneuvers. Steps are historical route content, not live navigation instructions. This field does not request toll prices.

## `maxStepsPerRoute` (type: `integer`):

Maximum turn-by-turn steps kept across each route when steps are enabled. The default is 50 and accepted values are one through 100; truncation is reported through warnings. This value has no effect while steps are disabled. It is not a distance or time limit.

## Actor input object example

```json
{
  "routeProvider": "SERPAPI_GOOGLE_MAPS",
  "googleMapsApiKey": "AIzaYOUR_RESTRICTED_KEY",
  "origin": "40.7580,-73.9855",
  "destination": "Central Park, New York, NY",
  "intermediates": [
    "Grand Central Terminal, New York, NY"
  ],
  "travelMode": "DRIVE",
  "routingPreference": "TRAFFIC_UNAWARE",
  "computeAlternativeRoutes": true,
  "maxRouteOptions": 1,
  "avoidTolls": false,
  "avoidHighways": false,
  "languageCode": "en",
  "units": "METRIC",
  "includeSteps": false,
  "maxStepsPerRoute": 50
}
```

# Actor output Schema

## `routeOptions` (type: `string`):

One normalized Google Maps route option per dataset record with its provider and source.

## `runSummary` (type: `string`):

Detailed terminal outcome, response counts, and safe diagnostics.

## `compactOutput` (type: `string`):

Stable compact terminal result for agents and automations.

## `lastRunSummary` (type: `string`):

Compatibility alias for the detailed terminal result.

# 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 = {
    "routeProvider": "SERPAPI_GOOGLE_MAPS",
    "origin": "Times Square, New York, NY",
    "destination": "Central Park, New York, NY",
    "travelMode": "DRIVE",
    "routingPreference": "TRAFFIC_UNAWARE",
    "computeAlternativeRoutes": true,
    "maxRouteOptions": 1,
    "avoidTolls": false,
    "avoidHighways": false,
    "languageCode": "en",
    "units": "METRIC",
    "includeSteps": false,
    "maxStepsPerRoute": 50
};

// Run the Actor and wait for it to finish
const run = await client.actor("khadinakbar/google-maps-directions-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 = {
    "routeProvider": "SERPAPI_GOOGLE_MAPS",
    "origin": "Times Square, New York, NY",
    "destination": "Central Park, New York, NY",
    "travelMode": "DRIVE",
    "routingPreference": "TRAFFIC_UNAWARE",
    "computeAlternativeRoutes": True,
    "maxRouteOptions": 1,
    "avoidTolls": False,
    "avoidHighways": False,
    "languageCode": "en",
    "units": "METRIC",
    "includeSteps": False,
    "maxStepsPerRoute": 50,
}

# Run the Actor and wait for it to finish
run = client.actor("khadinakbar/google-maps-directions-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 '{
  "routeProvider": "SERPAPI_GOOGLE_MAPS",
  "origin": "Times Square, New York, NY",
  "destination": "Central Park, New York, NY",
  "travelMode": "DRIVE",
  "routingPreference": "TRAFFIC_UNAWARE",
  "computeAlternativeRoutes": true,
  "maxRouteOptions": 1,
  "avoidTolls": false,
  "avoidHighways": false,
  "languageCode": "en",
  "units": "METRIC",
  "includeSteps": false,
  "maxStepsPerRoute": 50
}' |
apify call khadinakbar/google-maps-directions-api --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,khadinakbar/google-maps-directions-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/s6nFdlYPPIz3FcSt0/builds/AQSdLq6dd7ZG12Zpr/openapi.json
