# Geocode

> Turn latitude/longitude into city, country, admin region and timezone offline, plus haversine distance

This page includes setup, release pins, credentials, hosting and verification evidence. [JSON alternative](https://query.farm/products/orchard/api/v1/connectors/geocode.json) contains the same setup facts for structured readers; choose one format.

## Runtime and release

Use DuckDB or Haybarn **2.0.1** with **VGI protocol 3.4**.
Catalog alias: `geocode`. Release: [v0.5.0](https://github.com/Query-farm/vgi-geocode/releases/tag/v0.5.0). Metadata generated: 2026-12-01T18:22:16+00:00.

## Choose where it runs

- On your machine: use an installation method below. No Query Farm account is required for local execution.
- Self-host: follow [the connector deployment instructions](https://github.com/Query-farm/vgi-geocode) and [connection guide](https://query.farm/vgi/connect-to-a-worker/). Use your real endpoint and its authentication settings.
- Query Farm hosted: [create a deployment](https://auth.queryfarm.cloud/console/new?worker=geocode). Hosting has a $10 monthly minimum per organization; usage and license fees may apply. Copy the deployment-specific ATTACH from the console.

## Service credentials and prerequisites

No service credentials are declared by this connector. Individual datasets, input files or deployments may have their own prerequisites.

Secret parameter required flags describe the upstream declaration; they do not override the service-level mode above. Keep secrets in environment variables or the deployment secret store. SQL values in angle brackets are placeholders, not automatic environment lookups. Native DuckDB and Haybarn 2.0.1 do not provide a SQL getenv() function, even when worker-supplied snippets mention it. Read environment variables in your application and pass credential values through client parameter bindings (for example, Python con.execute("CREATE SECRET stripe (TYPE stripe, api_key ?)", [os.environ["STRIPE_API_KEY"]]) after attaching the connector. Omit unused optional parameters and keep real values out of saved SQL and logs.

## Install the extension

In stock DuckDB:

```sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;
```

In Haybarn:

```sql
INSTALL vgi FROM community;
LOAD vgi;
```

## Attach the connector

The local recipes below pin the catalog release for repeatability. A public demo endpoint follows its deployed release.

### uvx

Attach with uvx

Needs uv. uvx builds the worker from its release tag on first attach and reuses the cached environment after that.

```sql
ATTACH 'geocode' AS geocode (
  TYPE vgi,
  LOCATION 'uvx --from git+https://github.com/Query-farm/vgi-geocode@v0.5.0 vgi-geocode-worker'
);
```

### Docker

Attach the signed image

Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.

```sql
ATTACH 'geocode' AS geocode (
  TYPE vgi,
  LOCATION 'oci://ghcr.io/query-farm/vgi-geocode:0.5.0'
);
```

## Add city and country names to coordinates

Service credentials required for this example: not declared by this example; check the connector requirements above.

```sql
SELECT lat, lon, geocode.main.nearest_city(lat, lon) AS city, geocode.main.country_code(lat, lon) AS country FROM (VALUES (40.7128, -74.0060), (48.8566, 2.3522), (35.6762, 139.6503)) AS t(lat, lon)
```

- [geocode.main.nearest_city — scalar_function](https://query.farm/products/orchard/connectors/geocode/objects/scalar_function.bWFpbg.bmVhcmVzdF9jaXR5.md): exact declaration for this example.
- [geocode.main.country_code — scalar_function](https://query.farm/products/orchard/connectors/geocode/objects/scalar_function.bWFpbg.Y291bnRyeV9jb2Rl.md): exact declaration for this example.

Execution evidence: **captured_result**.

```json
{
  "status": "captured_result",
  "capturedAt": "2026-12-01T06:16:30+00:00",
  "engineVersion": "2.0.1",
  "protocolVersion": "3.4.0",
  "releaseTag": "v0.5.0",
  "sample": {
    "columns": [
      "lat",
      "lon",
      "city",
      "country"
    ],
    "types": [
      "DECIMAL(6,4)",
      "DECIMAL(7,4)",
      "VARCHAR",
      "VARCHAR"
    ],
    "rows": [
      [
        40.7128,
        -74.006,
        "New York City",
        "US"
      ],
      [
        48.8566,
        2.3522,
        "Paris",
        "FR"
      ],
      [
        35.6762,
        139.6503,
        "Tokyo",
        "JP"
      ]
    ],
    "more": false
  }
}
```

## Connector reference

### Offline Reverse Geocoding in SQL

**Turn latitude/longitude coordinates into the nearest city, country, admin regions and IANA timezone -- entirely offline, with no API keys, no rate limits and no network calls -- directly in DuckDB.**

`geocode` is a VGI worker that brings fast, hermetic **reverse geocoding** to SQL. Point it at any column of `(lat, lon)` coordinates and it enriches each row with the nearest known place name, its ISO-3166 country code, first- and second-level administrative regions (state/region, county/district), and the local IANA timezone. Because every lookup runs against bundled spatial databases rather than a hosted geocoding API, it works on air-gapped hosts, scales to millions of rows without per-request billing, and returns deterministic results. It is built for data engineers, analysts and GIS practitioners who need to attach human-readable geography and time zones to coordinate data sets -- IoT and GPS traces, telemetry, event logs, store/asset locations -- without leaving the database.

Under the hood, place lookups are powered by [`reverse_geocoder`](https://github.com/thampiman/reverse-geocoder) ([PyPI](https://pypi.org/project/reverse_geocoder/)), which queries a [GeoNames](https://www.geonames.org/) cities KD-tree to find the nearest populated place in sub-millisecond time. Timezone resolution uses [`timezonefinder`](https://github.com/jannikmi/timezonefinder) ([documentation](https://timezonefinder.readthedocs.io/)), which maps a point to its [IANA time-zone](https://www.iana.org/time-zones) polygon offline. Distances are computed with the great-circle [haversine formula](https://en.wikipedia.org/wiki/Haversine_formula). Every function is total and NULL-safe: a NULL or out-of-range coordinate yields `NULL` rather than an error, so the functions are safe to drop into large batch queries.

## What you can do

The worker groups its capabilities into three areas:

- **Place lookup** -- resolve a coordinate to the nearest city, its ISO-3166 country, and first- and second-level administrative regions (state/region and county/district), either one attribute at a time or as a single combined `STRUCT` record for the whole place.
- **Timezone** -- map a coordinate to its IANA timezone name (e.g. `America/New_York`) for localizing timestamps.
- **Distance** -- measure the great-circle (haversine) distance in kilometers between two coordinates.

Every operation is a per-row scalar you can use inline in any projection or predicate, so enriching a whole coordinate column -- or filtering it by proximity -- is a single `SELECT` with no joins, staging tables, or API round-trips.

Backed by GeoNames cities (`reverse_geocoder`, LGPL-3.0, used as an unmodified dependency) and offline IANA timezone polygons (`timezonefinder`, MIT).

## Find the exact SQL object

[Browse 7 object declarations](https://query.farm/products/orchard/api/v1/connectors/geocode/objects.json) or [search within this connector](https://query.farm/products/orchard/api/v1/search.json?kind=object&connector=geocode&q=geocode).

Follow one format of each needed object for complete argument types, defaults, named flags, return columns and examples. Existing links above can replace another search. For questions about hosting, credentials or supported operations, stop once the documentation answers the question; SQL and unrelated object lookups are unnecessary.

## Verification and interpretation

- Missing, null, or undeclared metadata means unknown; do not invent defaults, credential scope, platform support or endpoint URLs.
- Search is keyword retrieval, not proof of a capability. Read the exact object declaration before generating SQL.
- A table and a table function can have the same name. Preserve parentheses and use the matching overload and schema.
- Service credentials, external data availability and deployment authentication are separate requirements.
- Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL.

```json
{
  "generatedAt": "2026-12-01T18:22:16+00:00",
  "repository": "https://github.com/Query-farm/vgi-geocode",
  "harvest": {
    "status": "ok",
    "method": "subprocess",
    "error": null,
    "vgi_version": "9773130dde"
  },
  "catalogVerification": {
    "verified": true,
    "status": "passed",
    "total": 7,
    "passed": 7,
    "failed": 0,
    "needs_credentials": 0,
    "location": "uvx --from git+https://github.com/Query-farm/vgi-geocode@v0.5.0 vgi-geocode-worker",
    "transport": "subprocess",
    "environment": {
      "vgi_extension_version": "9773130dde",
      "haybarn_version": "2.0.1rc3",
      "engine_version": "v2.0.1",
      "python": "3.12.4",
      "platform": "darwin_arm64",
      "protocol_version": "3.4.0"
    },
    "checked_at": "2026-12-01T06:13:16+00:00"
  },
  "interpretation": "Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL."
}
```
