---
title: Search by location
description: Give a table a spatial index, then find the rows inside a box or nearest a point, on a map or on a plane.
related:
  - /data/define-tables
  - /data/walk-a-graph
  - /sdk/db
---

A `where` on two number columns can find rows inside a box, but it cannot rank rows by distance. A spatial index over a table's two coordinate columns finds rows inside a box and the rows nearest a point.

## Find the rows nearest a point

Add `spatial` to a table's options, naming its `x` and `y` columns. With `geo: true`, `x` is longitude and `y` is latitude, in degrees, and distances are in metres.

```ts luna/lunas/user.ts
import { defineLuna, t, table } from "luna";

export const User = defineLuna({
  name: "User",
  key: { id: t.string() },
  schema: {
    places: table(
      {
        id: t.id(), name: t.string(), kind: t.string(),
        lng: t.float(), lat: t.float(),
      },
      { spatial: { x: "lng", y: "lat", geo: true } },
    ),
  },
  handlers: (h) => ({
    near: h(
      { args: { lng: t.float(), lat: t.float() }, query: true },
      (ctx, { lng, lat }) =>
        ctx.db.places
          .nearby({ x: lng, y: lat }, { k: 5 })
          .map((hit) => ({ name: hit.row.name, metres: Math.round(hit.distance) })),
    ),
  }),
});
```

`nearby` returns hits nearest first, each with the `row` and its `distance`. `k` sets how many, 10 by default and at most 1,000.

Luna keeps the index in step as rows are added, moved and deleted. The `x` and `y` columns are `t.int()`, `t.float()` or `t.timestamp()` columns. A row with `null` in either is left out of the index, so it is never found.

## Limit the distance

`maxDistance` leaves out rows farther than it, in metres for a `geo` table.

```ts luna/lunas/user.ts
ctx.db.places.nearby({ x: lng, y: lat }, { k: 5, maxDistance: 2000 });
```

## Find the rows inside a box

`within` returns the rows whose point is inside a box, edges included. On a map, the box is the visible part of the map, in degrees.

```ts luna/lunas/user.ts
inView: h(
  {
    args: { minX: t.float(), minY: t.float(), maxX: t.float(), maxY: t.float() },
    query: true,
  },
  (ctx, { minX, minY, maxX, maxY }) =>
    ctx.db.places.within({ minX, minY, maxX, maxY }, { limit: 100 }),
),
```

`within` takes `limit`, and returns every row inside the box without it.

## Narrow the results with where

Both methods take a `where` with the operators of [Read and write rows](/data/read-and-write-rows).

```ts luna/lunas/user.ts
ctx.db.places.nearby({ x: lng, y: lat }, { k: 5, where: { kind: "cafe" } });
```

## Measure on a plane

Without `geo`, `x` and `y` are any units you choose, and distances are straight lines in the same units. Seats in a room, or points on a game board, fit this.

```ts luna/lunas/room.ts
seats: table(
  { id: t.id(), x: t.float(), y: t.float() },
  { spatial: { x: "x", y: "y" } },
),
```

## Measure between two points

[`geoDistance`](/sdk/db) gives the distance in metres between two points on the Earth, each as longitude then latitude in degrees.

```ts luna/lunas/user.ts
import { geoDistance } from "luna";

const metres = geoDistance(home.lng, home.lat, place.lng, place.lat);
```

`nearby` measures `geo` distances the same way.

## Next steps

- [Walk a graph](/data/walk-a-graph) follows links between rows.
- [Query across lunas](/data/query-across-lunas) searches the rows of many lunas at once.
- [ctx.db](/sdk/db) lists the options of `within` and `nearby`.
