# POST /maps-search: search Google Maps for businesses

> POST /maps-search finds businesses on Google Maps by category and location. Batch up to 1,000 keywords and 100 locations per call, with rating, review and website filters.
>
> Part of the LocalPipe API reference: https://www.localpipe.io/docs/maps-search (full reference in one file: https://www.localpipe.io/localpipe-api-docs.md, categories CSV: https://www.localpipe.io/localpipe-business-categories.csv)

## POST /maps-search

Search Google Maps for businesses by keyword and location. Returns business names, phone numbers, addresses, ratings, websites, and more. All requests are **asynchronous** — returns a `task_id` immediately.

> ### ⚡ BATCH YOUR LOCATIONS — ALWAYS
>
> **Never loop cities.** `/maps-search` accepts an array of **up to 100 locations** in one call and fans them out in parallel under one `task_id`. This is MUCH faster, uses one rate-limit slot, and avoids dropped cities. Submitting one request per city is the #1 cause of incomplete data and rate-limit exhaustion.
>
> - ✅ **Correct:** `{ "query": "plumber", "location": ["Austin, TX","Dallas, TX","Houston, TX","San Antonio, TX"], "limit": 500 }`
> - ❌ **Wrong:** `for city in cities; do curl .../maps-search -d '{"query":"plumber","location":"'$city'"}'; done`
> - More than 100 locations? Split into the **minimum** number of batched requests (250 cities → 3 requests, not 250 requests of 1) and submit them through the `drain_queue` pattern in the Agent Mode section.

> ### ✅ BATCHING KEYWORDS IS SAFE
>
> `limit` is the total budget for the task, but it is **split evenly across every keyword × location pair**, so batching keywords no longer starves the later ones.
>
> | Your `limit` | What to do with keywords | Why |
> |---|---|---|
> | `"all"` / `null` (Find ALL) | **Batch freely** — up to 1,000 keywords in one `query` array | No budget to split; every keyword is exhausted independently |
> | Integer (e.g. `500`) | **Batch freely** — each pair gets `limit ÷ pairs` | Unused share from dry pairs is redistributed to pairs that still have matches |
> | Need a guaranteed N per keyword | Pass `limit = N × number_of_pairs` | Each pair's share then works out to N |
>
> With an integer `limit`, a batch of 5 keywords × 1 location and `limit: 500` gives each of the 5 pairs a starting share of 100, and any share a pair cannot use is redistributed to the others. A pair that comes back with `found: 0` is a real empty market, not truncation. Confirm with `sub_query_breakdown`.


### Sizing `limit`

`limit` is the ceiling for the whole task (max 1,000,000). To target N results per pair, set `limit = N × number_of_pairs` (pairs = keywords × locations) in **one** batched request:

| Shape | Ceiling |
|---|---|
| 1 request, `["plumber","roofer"]` × 1 city, `limit: 500` | 500 total, starting share 250 per keyword |
| 1 request, `["plumber","roofer"]` × 1 city, `limit: 1000` | 1,000 total, starting share 500 per keyword |

Each pair is capped at its even share first; if a pair has fewer matches than its share, the unused part goes to pairs that still have more. A pair only ends up with fewer than its share when it genuinely has fewer matches.


**Exact Category Matching:** Your `query` is matched against Google Maps' official business category taxonomy (e.g. "Plumber", "Dentist", "HVAC Contractor"). When a match is found, results are filtered to only include businesses with that exact category — eliminating irrelevant results. Each result includes a `matched_category` field showing which category it matched. If no exact category match is found, results are returned based on keyword relevance. **Custom keywords are still possible** — queries that don't match Google's taxonomy are accepted and run as relevance searches, but they will not populate `matched_category`.

### Request Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| query | string or string[] | Yes | Business type/keyword(s). **Pass as an array to batch up to 1,000 keywords in ONE request** instead of looping — e.g. `["plumbers","hvac contractor","electrician"]`. Matched against Google Maps category taxonomy for exact filtering. |
| location | string or string[] | Yes | City names, state names, country names, US ZIP codes, or UK postcodes. **Pass as an array to batch up to 100 locations in ONE request** instead of looping — e.g. `["Austin, TX","Dallas, TX","Houston, TX"]`. Do NOT submit one request per city. |
| limit | integer \| "all" \| null | No | Total budget for the task. Default: 100, minimum: 50, max: 1,000,000. Values below 50 are raised to 50. ⚠️ **With multiple keywords and/or locations the budget is split evenly across every (query × location) pair**, and any share a dry pair cannot use is redistributed to pairs that still have more matches. 2 queries × 4 locations with `limit: 400` → 8 pairs, 50 each, and unused shares flow to the pairs with more results. **Pass `"all"` (or `null`) for Find ALL mode** — no budget at all, every pair returns everything Google has. |
| filters | object | No | Filter results (see Filter Options below) |
| callback_url | string | No | Webhook URL for result delivery when search completes |
| exclude_existing_lists | string[] | No | **Exclude already found.** Business List IDs to compare against. Any business already in those lists (matched by `place_id` or website domain) is removed from this task's results. Get the IDs from `GET /list-business-lists`. Max 50 lists per request. IDs that don't belong to your account return `400`. |

### Exclude Already Found

Pass `exclude_existing_lists` to get only businesses you do not already have. The exclusion is applied to the results of the task, so a `limit` of 500 can return fewer than 500 rows when many matches were already in your lists. Ask for more than you need if you require a guaranteed count.

```javascript
// 1. Look up your lists
const lists = await fetch("https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/list-business-lists", {
  headers: { "x-api-key": "YOUR_API_KEY" }
}).then(r => r.json());

// 2. Search, excluding everything already in those lists
const res = await fetch("https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/maps-search", {
  method: "POST",
  headers: { "Content-Type": "application/json", "x-api-key": "YOUR_API_KEY" },
  body: JSON.stringify({
    query: "plumbers",
    location: ["Austin, TX", "Dallas, TX"],
    limit: 1000,
    exclude_existing_lists: lists.lists.map(l => l.list_id)
  })
});
```

`GET /get-scrape-results` then reports how many were skipped:

```json
{
  "exclude_existing": {
    "lists_compared": 3,
    "excluded_from_results": 212,
    "note": "Businesses already present in the Business Lists you passed to /maps-search were removed from these results."
  }
}
```

### Filter Options

| Filter | Type | Description |
|--------|------|-------------|
| min_rating | number | Minimum Google rating (1-5) |
| max_rating | number | Maximum Google rating (1-5) |
| min_reviews | number | Minimum review count |
| max_reviews | number | Maximum review count |
| has_website | boolean | `true` returns only businesses **with** a website. `false` returns only businesses **without** a website (useful for web-design prospecting). Omit the field to allow both. |
| has_phone | boolean | `true` returns only businesses **with** a phone number. **Do not pass `false`** — it would exclude every listing that has a phone, which collapses yields (especially outside the US). Omit the field to allow both. |
| price_level | string[] | Google price ranges: ["$1-10", "$10-20", "$20-30", "$30-50", "$50-100", "$100+"]. Select one or more. Legacy $, $$, $$$, $$$$ remain supported; businesses without price data stay included. Most useful for restaurants/Hospitality. |
| opens_before | number | Business opens before this hour (0-23) |
| closes_after | number | Business closes after this hour (0-23) |
| radius_km | number | Search radius in kilometers around each ZIP/postcode location (3-80, default 25; values below 3 are raised to 3). Searches cover the radius around the ZIP/postcode center, not exact postal boundaries. Only applies to ZIP/postcode locations — ignored for city/state/country names. |

### Example Request

```javascript
const response = await fetch("https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/maps-search", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-api-key": "YOUR_API_KEY"
  },
  body: JSON.stringify({
    query: "plumbers",
    location: ["Austin, TX", "San Antonio, TX"],
    limit: 500,
    filters: {
      min_rating: 4.0,
      has_website: true,
      has_phone: true
    },
    callback_url: "https://your-webhook-url.com/maps-callback"
  })
});
```

### Multi-Keyword + Multi-Location Batch Example (Recommended)

This is the API's core strength: pass **all your keywords** and **all your cities** in a single call. Server-side fan-out runs every (keyword × location) pair in parallel and returns everything under one `task_id`.

```javascript
const response = await fetch("https://uunrlffonnvmbsstkpze.supabase.co/functions/v1/maps-search", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "x-api-key": "YOUR_API_KEY"
  },
  body: JSON.stringify({
    query: ["plumbers", "hvac contractors", "electricians", "roofers", "painters"],  // up to 1,000 keywords
    location: [
      "Austin, TX", "Dallas, TX", "Houston, TX", "San Antonio, TX", "Fort Worth, TX",
      "El Paso, TX", "Arlington, TX", "Corpus Christi, TX", "Plano, TX", "Lubbock, TX"
    ],  // up to 100 locations
    limit: 300,  // total budget, split evenly across all 50 pairs (6 each), unused share redistributed
    filters: {
      has_website: true,
      min_rating: 3.5
    },
    callback_url: "https://your-webhook-url.com/maps-callback"
  })
});
```

**What this single call does:**
- Fans out to **5 keywords × 10 locations = 50 parallel searches** server-side
- The **whole task** returns up to **300 leads total**, split evenly across the 50 pairs (6 each), with unused share from dry pairs redistributed to the rest
- Consumes **exactly 1 rate-limit slot** on submission (not 50)
- Want thousands of leads? Raise `limit`, or use `"limit": "all"` for full coverage

> ⚠️ **If you need more than 1,000 keywords or 100 locations:** split into the **minimum** number of batched requests. 250 cities → 3 requests (100, 100, 50 locations, all keywords in each). Never send one request per city or per keyword.

### Find ALL Mode vs. an integer limit

`limit` is the maximum number of results **for the whole task**, but it is shared out **per (query × location) pair** rather than first-come-first-served.

- **Integer limit** — the budget is divided evenly across pairs. For example, `query: ["plumber"], location: ["Austin, TX", "Dallas, TX"], limit: 300` gives each city a share of 150. If Austin only has 40 matches, the leftover 110 goes to Dallas, so the task still returns up to 300 in total. Want a guaranteed 300 per city? Pass `limit: 600` for two cities.
- **Find ALL (`"limit": "all"` or `null`)** — use this when you want **complete coverage** of every available lead in your areas. There is no budget at all; the scrape keeps pulling until Google stops returning new businesses for each pair.


Use Find ALL when the goal is "every business I can get in these locations." Use an integer when the goal is "give me up to N leads from this request in total."

```json
{
  "query": ["plumber", "electrician", "hvac contractor", "roofer", "painter"],
  "location": ["Tweed Heads, NSW", "Coolangatta, QLD", "Robina, QLD", "Burleigh Heads, QLD"],
  "limit": "all",
  "callback_url": "https://your-webhook-url.com/maps-callback"
}
```

**When to use Find ALL:**
- ✅ You want systematic coverage of a region (every plumber in these 20 postcodes)
- ✅ You want a multi-vertical industry sweep across a fixed footprint
- ✅ You'd rather receive "everything Google knows" than guess a per-area cap
- ❌ Skip it when you truly only want a top-N sample — pass an integer instead

Combined with multi-keyword × multi-location batching (up to 1,000 keywords × 100 locations under one `task_id`), a single Find-ALL request can return tens of thousands of leads.

> ### 🎯 How `limit` is applied
>
> `limit` is the total budget for the task, and for multi keyword × location jobs that budget is **divided evenly across every pair** before results are returned.
>
> Example: `query: ["plumber","electrician"]` + `location: ["Austin, TX","Dallas, TX"]` + `limit: 300` creates 4 pairs, so each pair starts with a budget of 75. If a pair has fewer matches than its share (or zero), the leftover is **redistributed** to the pairs that are still truncated, repeatedly, until the budget is spent or every pair is fully served. No pair can consume the whole task and starve the others, and no budget is wasted on dry pairs.
>
> `limit_scope` tells you how the budget was applied: `"per_keyword_location_pair"` when there is more than one pair (still one total budget, split evenly), `"task"` for a single keyword + single location, and `"all"` for Find ALL. The results response (`GET /get-scrape-results`) also includes `per_pair_budget` (each pair's starting even share, `floor(limit ÷ pairs)`) for multi-pair tasks with an integer limit; the 202 submit response does not.
>
> Want N leads per city or per keyword? Pass `limit = N × number_of_pairs`, or use `"limit": "all"` for exhaustive coverage.
>
> After the job completes, read `sub_query_breakdown` in the response to see how many leads were found vs. returned for **each location and each keyword**. `found: 0` means that pair genuinely had no matches. This field is returned only for multi keyword × location tasks — single keyword + single location tasks omit it.



### Response (202 Accepted)

```json
{
  "success": true,
  "task_id": "uuid-here",
  "status": "pending",
  "query": ["plumbers"],
  "locations": [
    { "input": "Austin, TX", "resolved": "Austin, US" },
    { "input": "San Antonio, TX", "resolved": "San Antonio, US" }
  ],
  "limit": 500,
  "limit_scope": "per_keyword_location_pair",
  "message": "Search queued. Poll GET /get-scrape-results?task_id=uuid-here for results."
}
```
