Blog·Craft·

City search ranks, it does not alphabetize

City search puts exact primary-name matches first, then ranks matching names by population to make the results useful in a picker.

When someone types char into a city picker, an alphabetical list puts Charleston ahead of Charlotte. That order is tidy, but it isn't necessarily the most useful order for someone trying to find their city.

In API 2.0.0, GET /city?q=char&country=US&limit=5&deep=true includes population inside each result's deep on a paid plan. This excerpt uses the population figures from the original example:

{
  "q": "char",
  "country": "US",
  "cities": [
    { "name": "Charlotte", "state": "NC", "deep": { "population": 943476 } },
    { "name": "Charleston", "state": "SC", "deep": { "population": 157665 } },
    { "name": "Charleston", "state": "WV", "deep": { "population": 46482 } },
    { "name": "Charlottesville", "state": "VA", "deep": { "population": 44767 } },
    { "name": "Charleston", "state": "IL", "deep": { "population": 17361 } }
  ]
}

City search puts an exact match on the primary name first. After that, it prefers matches on the primary name over alternate names, with population deciding the order within those groups. In this example, the primary names all start with char, so Charlotte leads on population.

The ranking also applies without deep=true. A basic response keeps the city names, state codes, and other location fields needed for a picker. Requesting detail lets you read the population used in that ordering. The City reference lists the optional fields.

That gives a picker a useful starting order without pretending to know which place the user meant. Keep the state visible, let them choose, and pass country or state when your form already knows them. limit controls how many suggestions come back.

You can still sort the result alphabetically if that's what your interface needs. The default is aimed at finding a place while someone is typing.