# Locations: suggest, boundaries, map box, drawn and saved shapes

Source: https://help.ruuster.com/idx/guide-locations

> Every way to say where to search, from suggest rows and boundary ids to ZIP, city and state, map boxes, drawn areas, saved shapes and named places, and how to combine and exclude them.

Every search needs a location, unless it asks for your own listings, one agent's or one office's.
This guide covers each kind of location, how to combine several, how to exclude one, and how to draw
the area on a map.

## Suggest rows: the location a visitor typed

`GET /v1/suggest?q=…` turns what a visitor typed into rows they can pick. Each row has a `group`, a
`label` to show and a `where` object to search with.

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/suggest" \
  --data-urlencode q=Atlanta \
  --data-urlencode groups=city,zip,neighborhood,place \
  --data-urlencode limit=5 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.suggest({
  q: "Atlanta",
  groups: ["city", "zip", "neighborhood", "place"],
  limit: 5,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/suggest",
    params={
        "q": "Atlanta",
        "groups": "city,zip,neighborhood,place",
        "limit": "5",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'q' => 'Atlanta',
    'groups' => 'city,zip,neighborhood,place',
    'limit' => '5',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/suggest' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

- **Pass the `where` object back exactly as you got it**, as JSON in the `where` parameter. It is
  opaque: never build one by hand or change its fields.
- **The groups** are address, listing (MLS numbers), city, zip, neighborhood, county, countyOrParish,
  school, subdivision, area, community and place. Without `groups` you get the default set, which
  leaves out MLS numbers; ask for `groups=listing` to add them.
- **Place rows** are named areas with an outline: cities and towns, ZIP areas, counties,
  neighborhoods, subdivisions and school districts in the states your boards cover. They work like any
  other row.
- **Debounce suggest.** Send a call once the visitor has typed at least three characters and paused
  for 300 ms, and cancel the call in flight when they type again. The `SearchBox` recipe component
  does this for you.
- **On the server,** suggest runs with the secret key too. Use it to look up each area once when you
  build your area list, then store the `where` object with the area.

## ZIP code, city and state, without suggest

For readable URLs and simple pages you can name a ZIP code, a city or a state directly:

- `zip=30308` matches that five-digit ZIP code.
- `city=Atlanta` matches that city in every state your boards cover; add `state=GA` to name one.
- `state=GA` matches the whole state.

Each counts as a location. When you send both `zip` and `city`, the ZIP code is searched.

## A boundary id

`boundariesId` takes a boundary id from a suggest row (neighborhood, county, subdivision, area or
community). It searches exactly as that row's `where` object would. An unknown id answers 404
`boundary_not_found`. For a ZIP code, use the suggest row's `where` object or `zip`.

## A map box

`bbox` is the visible map: `south,west,north,east` in decimal degrees, the order Google Maps'
`LatLngBounds.toUrlValue()` gives. A box can be at most 20 degrees on a side; a larger one answers
400 `area_too_large`.

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode bbox=33.70,-84.45,33.85,-84.30 \
  --data-urlencode status=active \
  --data-urlencode limit=24 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.search({
  bbox: "33.70,-84.45,33.85,-84.30",
  status: "active",
  limit: 24,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "bbox": "33.70,-84.45,33.85,-84.30",
        "status": "active",
        "limit": "24",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'bbox' => '33.70,-84.45,33.85,-84.30',
    'status' => 'active',
    'limit' => '24',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

When a visitor pans or zooms, wait 300 ms after the map stops moving before you search, and cancel
the call in flight when it moves again.

## A drawn area

`polygon` is an area a visitor drew: `lat,lng,lat,lng,…` with at least three points. Repeat the
parameter for several rings. All the rings together can have at most 200 points.

## A point and a radius

`near=lat,lng` searches around a point, such as where an agent is standing: the listings within
`radiusMiles` of it. The radius is 1 mile when you leave it out, and at most 25 miles; decimals such
as `0.5` work. This search finds active homes within a mile of a point in Midtown Atlanta:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode near=33.7701,-84.3857 \
  --data-urlencode radiusMiles=1 \
  --data-urlencode status=active \
  --data-urlencode limit=24 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.request("/listings", {
  near: "33.7701,-84.3857",
  radiusMiles: "1",
  status: "active",
  limit: "24",
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "near": "33.7701,-84.3857",
        "radiusMiles": "1",
        "status": "active",
        "limit": "24",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'near' => '33.7701,-84.3857',
    'radiusMiles' => '1',
    'status' => 'active',
    'limit' => '24',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

`near` is a location on its own. Combined with a `where`, `zip`, `city`, `state`, `boundariesId`,
`shape`, `ownListings`, `agent` or `office`, the search answers 400, because each would add
listings outside the circle. A `bbox`, a `polygon` and an excluded `where` narrow it. A point that
is not `latitude,longitude` in range, or a radius over 25 miles, answers 422
`location_not_supported` with a message that says what to send.

## A saved shape

Your account can hold saved shapes, such as a country club, a farm area or a school zone drawn
once. To have a shape added to a live account, email `helpme@ruuster.com`. The sandbox has none. `GET /v1/shapes` lists them and `GET /v1/shapes/{shapeId}` returns one outline. Search inside
one with `shape=shp_…`.

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode shape=shp_WorldClub001 \
  --data-urlencode status=active \
  --data-urlencode limit=24 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.search({
  shape: "shp_WorldClub001",
  status: "active",
  limit: 24,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "shape": "shp_WorldClub001",
        "status": "active",
        "limit": "24",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'shape' => 'shp_WorldClub001',
    'status' => 'active',
    'limit' => '24',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

## Several areas at once

Repeat `where` to search several areas together: up to 20 in one search. A listing in any of them
matches. You can mix `where` with `zip`, `city`, `state`, `boundariesId`, `bbox`, `polygon` and
`shape`; each adds its area to the search. `near` is the one location that stands alone.

## Leaving an area out

Add `"operator":"not"` to a `where` object to exclude that area. This search covers Atlanta and
leaves out Midtown:

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode 'where={"label":"Atlanta, GA","value":"Atlanta","source":"crm-system","city":"Atlanta","state":"GA"}' \
  --data-urlencode 'where={"label":"Midtown, Atlanta, GA","value":"a0000000-0000-4000-8000-000000000001","source":"neighborhood","operator":"not"}' \
  --data-urlencode limit=24 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.search({
  where: [{
    label: "Atlanta, GA",
    value: "Atlanta",
    source: "crm-system",
    city: "Atlanta",
    state: "GA",
  }, {
    label: "Midtown, Atlanta, GA",
    value: "a0000000-0000-4000-8000-000000000001",
    source: "neighborhood",
    operator: "not",
  }],
  limit: 24,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "where": ["{\"label\":\"Atlanta, GA\",\"value\":\"Atlanta\",\"source\":\"crm-system\",\"city\":\"Atlanta\",\"state\":\"GA\"}", "{\"label\":\"Midtown, Atlanta, GA\",\"value\":\"a0000000-0000-4000-8000-000000000001\",\"source\":\"neighborhood\",\"operator\":\"not\"}"],
        "limit": "24",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

// Repeated names are sent once per value: http_build_query would add [] to them.
$pairs = [
    ['where', '{"label":"Atlanta, GA","value":"Atlanta","source":"crm-system","city":"Atlanta","state":"GA"}'],
    ['where', '{"label":"Midtown, Atlanta, GA","value":"a0000000-0000-4000-8000-000000000001","source":"neighborhood","operator":"not"}'],
    ['limit', '24'],
];
$query = implode('&', array_map(fn ($p) => rawurlencode($p[0]) . '=' . rawurlencode($p[1]), $pairs));
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

## Your own, an agent's or an office's listings

`ownListings=1`, `agent=<slug or id>` and `office=<MLS office id>` need no location. They add their
listings together, and a map box, a drawn area, an excluded area and the other filters narrow them.
Don't combine them with an included area or a `boundariesId`: that search answers 400, because the
area would add listings rather than narrow them. See
[Recipes: our listings](https://help.ruuster.com/idx/recipe-our-listings) and
[one agent's listings](https://help.ruuster.com/idx/recipe-agent-listings).

## Hidden addresses inside a box, a drawn area or a shape

A listing whose address is hidden is never placed on a map. So inside a map box, a drawn area, a
`near` circle or a saved shape, those listings are left out of the results. A search by a named place, such as a city,
a ZIP code or a neighborhood, includes them, with the address masked.
[Hidden addresses and maps](https://help.ruuster.com/idx/compliance-hidden-addresses) has the rules.

## Drawing the area on your map

Each search answer tells you what to draw:

- `data.viewport` is the box to fit the map to, and `data.viewportSource` says where it came from:
  `boundary`, `library`, `shape`, `drawn` or `results`.
- `data.boundary` is set when the search named an area with an outline. `GET` its `href`
  (`/v1/boundaries/{boundaryId}` or `/v1/shapes/{shapeId}`) for the outline as GeoJSON and draw it
  under the pins. `AreaMap` does both.

## Location errors

| Error | What it means |
|---|---|
| 400 `location_required` | The search named no location and no own, agent or office listings. |
| 400 `area_too_large` | The box or the drawn area is too large. Zoom in or simplify it. |
| 404 `boundary_not_found` | The boundary id is unknown. Ask suggest again. |
| 404 `shape_not_found` | The shape id is not one of this key's saved shapes. |
| 422 `location_not_supported` | That kind of location can't be searched. Use a suggest row, a box or a drawn area. For `near` and `radiusMiles`, the message says what was wrong with the point or the radius. |

Every parameter is on [Search listings](https://help.ruuster.com/idx/listings-search).
