# Offline City Geocoder: City Name to Coordinates (`serenade/offline-city-geocoder`) Actor

Turn messy city text like "Austin, TX", "München" or "서울" into coordinates, country, region, population and time zone. Runs fully inside the Actor: no API key, no outside calls, no rate limits.

- **URL**: https://apify.com/serenade/offline-city-geocoder.md
- **Developed by:** [Henry Kang](https://apify.com/serenade) (community)
- **Categories:** Developer tools, Travel
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.09 / 1,000 resolved location

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/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

## Offline City Geocoder: City Name to Coordinates

Turn messy place text such as **"Austin, TX"**, **"München"**, **"Toronto, ON"**, **"Sài Gòn"** or **"서울특별시"** into **coordinates, country, region, population and IANA time zone**.
Everything runs inside the Actor. There is **no API key, no call to an outside geocoding service, and no rate limit**.
City level only: no street addresses or postal codes. **$0.085 per 1,000 resolved locations**; texts that are not resolved are free.
Give the texts as a JSON list in **Locations** (one entry per text). Reading place texts straight from another Apify dataset is not offered in this version.

### What you get for each text

| Field | Example | Meaning |
|---|---|---|
| `query` | `Austin, TX` | Your text |
| `status` | `ok` | `ok`, `not_found`, `country_only`, `region_only` or `invalid_input`. Only `ok` is charged |
| `matchedName` | `Austin` | The city that was matched |
| `countryCode`, `countryName` | `US`, `United States` | Country, with the name in the language you choose |
| `admin1`, `admin1Code` | `Texas`, `TX` | First-level region (state, province) |
| `latitude`, `longitude` | `30.26715, -97.74306` | City coordinates |
| `population` | `974447` | Population from GeoNames |
| `timezone` | `America/Chicago` | IANA time zone of the city |
| `geonameId` | `4671654` | GeoNames ID, handy for joins |
| `confidence` | `high` | `high`, `medium` or `low`, depending on how clearly one city wins |
| `candidates` | `6` | How many cities share the matched name, before hints are applied |
| `alternatives` | `[...]` | Up to three other cities with the same name (can be turned off) |
| `hintsIgnored` | `["Atlantis"]` | Parts of your text that did not match any country or region |

### What it understands

- **City names in many languages and scripts**: "München" and "Munich", "서울" and "Seoul", "東京" and "Tokyo", "Sài Gòn" and "Ho Chi Minh City". Accents are optional: "Sao Paulo" finds "São Paulo".
- **Country and region hints after a comma**: "Paris, TX", "Melbourne, VIC", "Toronto, ON", "London, UK", "Munich, Germany".
- **Hints without a comma**: "Paris TX", "Berlin Germany".
- **Postal codes next to a hint are skipped**: "Paris, TX 75460" still uses the "TX" hint.
- **Everyday extras**: "Greater London", "Greater Seattle Area", "Bay Area", "New York City", "서울특별시", "부산광역시".
- **Ambiguous names** are resolved toward the larger and more important city, unless a hint says otherwise. "Springfield, IL" gives Springfield, Illinois. Check `confidence` and `alternatives` when it matters.
- A `country` value in an entry (for example `{"query": "Paris", "country": "US"}`) is used as a hint. A **default country** can be set for data from one country.

What is not charged:

- Texts that only name a country ("Germany", "Brazil", "Mexico", "Panama") come back as `country_only`, not as the capital. City states ("Singapore", "Monaco", "Hong Kong") are matched as cities.
- Texts that only name a state or region ("California, United States", "West Virginia", "Florida"), or only a state code ("WA", "NSW"), come back as `region_only`. They are not matched to small towns that happen to share the name. Capitals and cities of 1,000,000+ people that share a region's name ("New York", "Seoul") are still treated as cities.
- When a name is a city in one country and a region or a country elsewhere, a hint decides. "Manchester, UK" (or `"country": "GB"`) is the city in England; "Manchester, Jamaica" is the parish and comes back as `region_only`. "Granada, Spain" is the city, not Grenada. Without a hint, the city is chosen when a city with exactly that name has more people than all listed towns of the region together ("Manchester", "Portland", "Southampton"); otherwise the result is `region_only` ("Canterbury" gives the New Zealand region, "Canterbury, UK" the city).
- If a hint names a real country or region but no city of that name is there ("Paris, Japan"), the result is `not_found`.
- Placeholders and world regions ("Remote", "TBD", "None", "N/A", "Headquarters", "Home", "APAC", "EU", "Africa", "Central America") come back as `not_found`.

### How to use it

#### 1. Paste texts

```json
{
  "locations": [
    "Austin, TX",
    "München",
    { "id": "row-17", "query": "Springfield", "country": "US" },
    "서울특별시"
  ]
}
```

#### 2. Call it from your code, an integration, or an AI agent

Run it through the Apify API, from Make, Zapier or n8n, on a schedule, or as a tool for AI agents through the Apify MCP server.

### Output example

```json
{
  "inputIndex": 0,
  "id": null,
  "query": "Austin, TX",
  "status": "ok",
  "message": null,
  "matchedName": "Austin",
  "countryCode": "US",
  "countryName": "United States",
  "admin1": "Texas",
  "admin1Code": "TX",
  "latitude": 30.26715,
  "longitude": -97.74306,
  "population": 974447,
  "timezone": "America/Chicago",
  "geonameId": 4671654,
  "confidence": "high",
  "candidates": 6,
  "hintsIgnored": null,
  "alternatives": []
}
```

(`candidates` is 6 because six cities called Austin are known. The "TX" hint leaves only the one in Texas, so `alternatives` is empty. This example was made with our test copy of the data; on Apify the data is newer, so numbers such as `population` can differ.)

### Pricing

**$0.085 per 1,000 resolved locations** ($0.000085 each). For example, 10,000 resolved locations cost $0.85.
Each run also has the standard Apify start fee of $0.00005 (charged once per GB of memory, so $0.00005 at the default 1 GB).
Texts that are not found, only name a country or a region, or are empty are **not charged**.
If you set a maximum cost per run, the Actor stops cleanly when that amount is reached.

### Speed

In a local test on a laptop, the city index loaded in about 1 second, and matching 19,200 texts took about 1 second (matching only, before results are saved). On Apify, two test runs with 1,000 texts each took 3.4 and 5.4 seconds in total, start-up included. Speed on Apify depends on the memory you choose.

### Good to know

- This is a **city-level** geocoder. It does not find street addresses, postal codes, districts, landmarks or businesses.
- It knows the places in GeoNames' cities1000 list (in the data downloaded on 2026-11-24: about 172,000 places with about 830,000 names). Very small villages may be missing.
- Each entry must be a text or an object with a `query` text. Other values come back as `invalid_input` (not charged).
- Coordinates are the city's reference point from GeoNames, not a boundary.
- When a name is shared by several cities and there is no hint, the answer can be wrong. Use hints, a `country` value in the entry, or `defaultCountry`, and check `confidence` and `alternatives`. For example, "San Jose" alone gives San José, Costa Rica (a capital), and "Victoria" alone gives Hong Kong, whose alternate names include Victoria. "San Jose, CA" and "Victoria, BC" give the cities in the US and Canada.
- A text of 3 Latin letters or fewer that matches a town only through an alternate name, with no hint, gets `confidence: "low"`, because such matches are often airport or other codes. The match is still charged. Short names in other scripts, such as "東京", keep their normal confidence.
- Two-letter texts that are also country codes (for example "DE" or "IN") come back as `country_only`. "LA" and "DC" are read as Los Angeles and Washington, D.C., and are charged. If "LA" in your data means Louisiana, put it after the city ("Baton Rouge, LA").

### Data sources and licences

- Cities, alternate names and regions: [GeoNames](https://www.geonames.org/), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The latest data is downloaded each time the Actor is built. Changes made: reduced to the fields this Actor uses, names normalized and indexed. If the download fails, the build stops, so an old copy is never used by accident. The run's `SUMMARY` record (in the key-value store) gives the data source and the time it was built.
- Test data: the GeoNames copy in the `geonamescache` package (MIT), used only in local tests.
- Country names: Unicode CLDR, through the `babel` package.

### FAQ

**Is my data sent anywhere?** No. All matching happens inside the run.

**Can I get the result in CSV or Excel?** Yes. Export the run's dataset in any format that Apify offers.

**A city is matched wrongly.** Open an issue on the Issues tab and include the text.

# Actor input Schema

## `locations` (type: `array`):

Texts to resolve, such as "Austin, TX", "Munich, Germany", "Toronto, ON" or "서울". You can also give objects like {"id": "row-1", "query": "Paris", "country": "US"}; "country" is used as a hint.

## `defaultCountry` (type: `string`):

Two-letter ISO code, e.g. US or KR. When a text has no country hint, cities in this country are preferred.

## `countryNameLanguage` (type: `string`):

Language code for countryName, e.g. en, de, fr, es, ja, ko, vi, zh.

## `includeAlternatives` (type: `boolean`):

Add up to three other cities with the same name, so you can check ambiguous names like Springfield.

## `maxItems` (type: `integer`):

Stop after this many entries. Leave empty to process everything.

## Actor input object example

```json
{
  "locations": [
    "Austin, TX",
    "München",
    "Paris, TX",
    {
      "id": "seoul-office",
      "query": "서울특별시"
    },
    "Ho Chi Minh City"
  ],
  "countryNameLanguage": "en",
  "includeAlternatives": true
}
```

# Actor output Schema

## `results` (type: `string`):

One row per input text: matched city, country, region, coordinates, population, time zone and confidence, or a status and message when no city was found.

# 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 = {
    "locations": [
        "Austin, TX",
        "München",
        "Paris, TX",
        {
            "id": "seoul-office",
            "query": "서울특별시"
        },
        "Ho Chi Minh City"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("serenade/offline-city-geocoder").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 = { "locations": [
        "Austin, TX",
        "München",
        "Paris, TX",
        {
            "id": "seoul-office",
            "query": "서울특별시",
        },
        "Ho Chi Minh City",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("serenade/offline-city-geocoder").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 '{
  "locations": [
    "Austin, TX",
    "München",
    "Paris, TX",
    {
      "id": "seoul-office",
      "query": "서울특별시"
    },
    "Ho Chi Minh City"
  ]
}' |
apify call serenade/offline-city-geocoder --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,serenade/offline-city-geocoder"
        }
    }
}
```

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/oYPy55bduwaWZDebK/builds/QTMr0eOUsNE5fiuXc/openapi.json
