Skip to Content
teigeodata
Languages

Kotlin and Java

teigeodata on the JVM and Android: one library for Kotlin and Java, offline geocoding with rows as maps.

One library serves Kotlin and Java, on desktop JVMs (Java 17 or later) and on Android (API 24 or later). It calls the native library through JNI; the JAR carries it for each desktop platform, the AAR for each Android ABI (arm64-v8a, armeabi-v7a, x86_64, 16 KB page aligned).

Every example on this page ran

The code below is cut from one program, the tour, which CI runs on the released public pack world-np-lite.tgd (data-2026.11.14.3) and checks line by line against the output shown here. The output is the same in every language.

Install

From the first registry release, on Maven Central:

build.gradle.kts
dependencies {
    implementation("com.teispace:teigeodata:1.0.0")            // desktop JVM
    // implementation("com.teispace:teigeodata-android:1.0.0") // Android
}

Get a pack

Queries read packs: signed, memory-mapped files of places. This guide uses the world lite pack: the world's countries, first-level units and cities of 5,000 or more, India's districts and statutory towns, and Nepal in full, 172,339 places named in Nepali, Hindi and English (15.6 MB, CC BY 4.0):

curl -LO https://github.com/teispace/teigeodata/releases/download/data-2026.11.14.3/world-np-lite.tgd
shasum -a 256 world-np-lite.tgd   # 243ae55509a538b1f61da50994a791cc78e7deb70bb4bf743b9f59d458cbe3f3

An app ships a pack inside its bundle, or downloads one when a user needs it. Once the signed catalog is live, the store does that download for you: it verifies every byte and keeps the packs updated.

Read a result

Every query returns a result blob (byte[]): the rows as compact columns, read in place. Reader reads it; iterating gives each row as a Map<String, Object> in column order, with null where a value is null. Values are String, Integer, Long, Float or Double, by the column's type:

for (place in Reader(engine.search("Pokhara", 3))) {
    println("${place["name"]} ${place["lat"]}")
}

For large results read whole columns: numbers("lat") is a double[], strings("name") a String[], nulls("elevation") a boolean[].

Open a pack

An Engine holds the packs it answers from. openFile memory-maps a pack file and adds it as a layer; the engine answers from every layer at once, and a higher layer wins where two disagree. Opening is cheap: the head of the file is read and checked and the block hashes of large sections are proved; each section is verified against its hash the first time a query reads it.

Tour.kt
Engine().use { engine ->
    engine.openFile(pack)
    println("layers: ${engine.layers()}")
Output
layers: 1
  • openBytes adds a pack from bytes already in memory (a download, an app asset, the browser). openFileRange opens a pack stored uncompressed inside another file, such as an Android APK.
  • Each …With form takes OpenOptions: precedence over the other packs, when sections are verified (lazy, eager or trusted), whether the file is mapped or read, and which components, languages and outline level to read.
  • openFile returns the layer's number; remove takes it out again while other threads keep querying. One engine answers from any number of threads at once.

Search by name

search finds places by name, best first. It matches every name a place has, in every script, and forgives spelling: काठमाडौं, Kathmandu and Kathamandu find the same city, and so do typos, missing accents and abbreviations. A result row has the place columns (id, name, kind, level, lat, lon, elevation, parent, tz, iso, population, population_kind) and a score.

Tour.kt
for (p in Reader(engine.search("Pokhara", 3))) {
    println("%s  %s  %s  %.4f, %.4f  score %d".f(p["id"], p["name"], p["kind"], p["lat"], p["lon"], p["score"]))
}
Output
tgd:np/1xhb  Pokhara  settlement  28.2669, 83.9680  score 132
tgd:np/1xnr  Pokhara  admin  28.2094, 83.9818  score 105
tgd:np/15t1  Pokhara  settlement  28.0636, 82.3786  score 90

The score ranks the rows of one query and means nothing across queries. It adds how well the name matched to how important the place is, so a city ranks above a village of the same name. limit is at most 10,000 (TeiGeodata.LIMIT_MAX).

Narrow a search by its parent

Write the place's parent after a comma, as people do: "Kathmandu, Bagmati". Places inside a unit of that name rank first; the parent can be any ancestor (a district, a province, a country) and is matched with the same tolerance as the name.

Tour.kt
for (p in Reader(engine.search("Kathmandu, Bagmati", 2))) {
    println("${p["id"]}  ${p["name"]}  ${p["kind"]} ${p["level"]}")
}
Output
tgd:np/2cn  Kathmandu  settlement 0
tgd:np/2gm  Kathmandu  admin 3

The city (a settlement, level 0) and the metropolitan municipality (an admin unit at level 3) share the name, and both are in Bagmati.

Rank by distance from a point

Many places share a name. searchWith takes SearchOptions: a focus point (the user's location, or the middle of the map they are looking at) ranks near places first. A place at the focus gains 30 points, one focusScaleM away 15, and the gain keeps halving with distance (the default scale is 50 km).

Tour.kt
// Many places share a name; a focus (the user's location) ranks the near ones first.
val options = SearchOptions(28.7, 80.6, 30_000.0, false)
for (p in Reader(engine.searchWith("Shivapur", 3, options))) {
    println("%s  %s  %.4f, %.4f".f(p["id"], p["name"], p["lat"], p["lon"]))
}
Output
tgd:np/2v99  Shivapur  28.5310, 80.8213
tgd:np/2raj  Shivapur  28.7141, 80.9869
tgd:np/2rkx  Shivapur  28.5061, 81.3032

Set strict to rank by how well the name matched first (exact, loose, prefix, one edit, substring, two edits, phonetic), then by importance and focus, instead of one combined score: useful for an autocomplete that must show exact matches on top.

Get a place by its ID

Every place has a stable ID such as tgd:np/1xhb: the country, then a short code. IDs survive rebuilds of the data; when two places are merged, get on the retired ID answers with the survivor, so IDs you stored keep working.

Tour.kt
val place = Reader(engine.get("tgd:np/1xhb")).single()
println("${place["name"]} ${place["kind"]}")
println("at %.6f, %.6f, %d m".f(place["lat"], place["lon"], place["elevation"]))
println("timezone ${place["tz"]} parent ${place["parent"]}")
Output
Pokhara settlement
at 28.266890, 83.968000, 1006 m
timezone Asia/Kathmandu parent tgd:np/1xnr

elevation is metres above mean sea level (EGM2008), tz the IANA zone and parent the ID of the unit that holds the place. Any column may be null where the data has no value: read each through the reader, which gives your language's null.

Walk the admin hierarchy

ancestors lists the units that hold a place, parent first, up to its country; parent gives the first of them alone and children the units and places one level down.

Tour.kt
for (p in Reader(engine.ancestors("tgd:np/1xhb"))) {
    println("${p["kind"]} ${p["level"]}  ${p["name"]}  ${p["iso"] ?: ""}".trimEnd())
}
val children = Reader(engine.children("tgd:np/295c"))
println("Kaski has ${children.rows()} children")
Output
admin 3  Pokhara
admin 2  Kaski
admin 1  Gandaki  NP-P4
country 0  Nepal  NP
Kaski has 5 children

level is the admin level as each country defines it: 0 is a country (and a settlement, which is not a unit), 1 a province or state, and so on down to the lowest level the data has. Each country's ladder is in its profile on the data pages.

Reverse geocode a point

reverse gives the places nearest a point, nearest first, each with meters (the great-circle distance) and bearing (degrees clockwise from north, from the place to the point: "3.2 km at 45° from Pokhara").

Tour.kt
for (p in Reader(engine.reverse(27.7172, 85.3240, 3))) {
    println("%s  %.0f m at %.0f°".f(p["name"], p["meters"], p["bearing"]))
}
Output
Narayanhiti Royal Palace  331 m at 116°
Gairidhara  375 m at 220°
Naxal  384 m at 329°

For the admin units that hold a point (its district, province and country) use adminAt below; reverse answers with what is near it.

Find everything within a radius

withinRadius gives the places within a distance of a point, nearest first, with the same meters and bearing columns, at most limit of them.

Tour.kt
val within = Reader(engine.withinRadius(27.7172, 85.3240, 500.0, 10)).records()
println("%d places within 500 m; farthest %.0f m".f(within.size, within.last()["meters"]))
Output
3 places within 500 m; farthest 384 m

Find places near a place

nearby is reverse geocoding from a place you already have: the places nearest it, itself left out.

Tour.kt
for (p in Reader(engine.nearby("tgd:np/2cn", 3))) {
    println("%s  %.0f m".f(p["name"], p["meters"]))
}
Output
Bhrikuti Mandap  168 m
Bagbazar  354 m
Shahidgate  393 m

Admin units at a point, and ISO 3166 codes

adminAt tests the point against the admin boundaries and gives every unit that holds it, country first. byIso finds a country or a subdivision by its ISO 3166 code (NP, NP-P4, in either case).

Tour.kt
for (p in Reader(engine.adminAt(28.2096, 83.9856))) {
    println("${p["level"]}  ${p["name"]}  ${p["iso"] ?: ""}".trimEnd())
}
val state = Reader(engine.byIso("NP-P4")).single()
println("NP-P4 is ${state["name"]} ${state["id"]}")
Output
0  Nepal  NP
1  Gandaki  NP-P4
2  Kaski
3  Pokhara
NP-P4 is Gandaki tgd:np/2922

Boundaries are exact polygons, so a point near a border is answered by the side it is on, not by the nearest centre. Disputed boundaries are drawn from one stated perspective; see accuracy.

Timezones: the zone, its offset and local times

tzAt gives the IANA zone at a point as the zone boundaries draw it. With the zone, tzOffsetAt gives the UTC offset at an instant (from the tzdb rules inside the pack, not from the operating system), and tzLocal tells whether a wall-clock time exists: unique, gap (skipped by a daylight-saving change) or overlap (it happens twice), with the offsets before and after.

Tour.kt
val zone = Reader(engine.tzAt(27.7172, 85.3240)).single()["tz"] as String
val offset = Reader(engine.tzOffsetAt(zone, 1_700_000_000)).single()
println("$zone ${offset["seconds"]} s east of UTC, ${offset["abbr"]} dst ${offset["dst"]}")
val local = Reader(engine.tzLocal("America/New_York", 2026, 3, 8, 2, 30, 0)).single()
println("02:30 on 2026-03-08 in New York: ${local["kind"]} ${local["before"]} -> ${local["after"]}")
println("tzdb ${engine.tzVersion()}")
Output
Asia/Kathmandu 20700 s east of UTC, +0545 dst 0
02:30 on 2026-03-08 in New York: gap -18000 -> -14400
tzdb 2026f

tzVersion names the tzdb release the rules come from, so you can tell when a pack is older than a rule change; tzZones lists every zone the packs hold.

Elevation at any point

elevationAt reads the terrain height at a point from the pack's elevation grid, interpolated between the four samples around it: meters above EGM2008, the source product, the grid's resolution_m and the datum. There is no row at sea or outside every grid.

Tour.kt
val height = Reader(engine.elevationAt(27.7172, 85.3240)).single()
println("%.1f m above %s (%s, %.0f m grid)".f(height["meters"], height["datum"], height["source"], height["resolution_m"]))
Output
1304.2 m above EGM2008 (nasadem, 464 m grid)

Every place also has its own elevation column. The world pack carries a coarse grid; a country's terrain pack adds a finer one, and the engine answers from the finest grid that covers the point.

Distance and bearing

distanceM is the great-circle distance in metres (haversine on the WGS84 mean sphere, within about 0.5% of the ellipsoid), and bearingDeg the initial bearing from the first point to the second, in degrees clockwise from north. Neither needs a pack. Between two places you already have, distance takes their IDs and answers one row with meters and bearing.

Tour.kt
val meters = TeiGeodata.distanceM(27.7172, 85.3240, 28.2096, 83.9856)
val heading = TeiGeodata.bearingDeg(27.7172, 85.3240, 28.2096, 83.9856)
println("Kathmandu to Pokhara: %.1f km, heading %.0f°".f(meters / 1000, heading))
val apart = Reader(engine.distance("tgd:np/2cn", "tgd:np/1xhb")).single()
println("place to place: %.1f km at %.0f°".f(apart["meters"] as Double / 1000, apart["bearing"]))
Output
Kathmandu to Pokhara: 142.4 km, heading 293°
place to place: 146.9 km at 296°

distance answers no row when either ID is unknown. From a point to a place, pass the place's lat and lon to distanceM. The bearing is the direction you set off in: on a great circle it changes along the way, so the bearing back is not the reverse of this one.

A place's outline

boundary answers a unit's outline as one row: geojson, an RFC 7946 Feature (a Polygon or MultiPolygon, outer rings counterclockwise and holes clockwise, seven decimals as stored), with the lod read, its tolerance_m and the number of vertices. A place with no outline answers its point as the geometry; an unknown ID answers no row.

Tour.kt
val shape = Reader(engine.boundary("tgd:np/2gm", 0)).single()
val geojson = shape["geojson"] as String // a GeoJSON Feature, for any map library
val type = geojson.substringAfter("\"geometry\":{\"type\":\"").substringBefore('"')
println("%s of %s vertices at level %s".f(type, shape["vertices"], shape["lod"]))
println("tolerance %.0f m, %d bytes of GeoJSON".f(shape["tolerance_m"], geojson.length))
Output
Polygon of 176 vertices at level 0
tolerance 0 m, 4362 bytes of GeoJSON

The Feature goes to a map as it is: MapLibre's and Leaflet's GeoJSON sources, OpenLayers, Shapely's shape(), Turf and JTS all read it.

  • Level of detail. lod 0 is full resolution; 1 to 6 are coarser, each within its tolerance_m, with neighbouring units still sharing their borders at every level. A pack stored at full resolution only (the lite packs) answers every level as 0. A country at level 0 can be megabytes: draw a coarser level, and keep 0 for measuring.
  • lod above 6 is InvalidArgument; a pack installed without boundaries is MissingComponent.
  • Whether a point is inside a unit is adminAt, which tests the same outlines without building them.

Errors

A call fails with one of eight stable codes, the same in every language:

CodeMeaning
InvalidArgumentAn argument is outside its range: a latitude of 91, a limit over 10,000, a malformed ID.
MissingComponentThe query needs a component the pack was installed without (search on a pack installed without search).
CorruptThe bytes are not a valid pack, or a section does not match its hash.
IoA file could not be read.
NetworkNo mirror answered, or the connection broke (the store only).
RefusedThe store refused: the catalog did not verify, a pack is not installed or another needs it.
CancelledA callback or a job was asked to stop.
InternalA bug inside teigeodata; a panic never crosses into your program.

A query that finds nothing is not an error: it returns no rows.

Each code is a subclass of the unchecked TeiGeodataException: TeiGeodataException.InvalidArgument, .MissingComponent and so on.

Tour.kt
try {
    engine.reverse(91.0, 0.0, 1)
} catch (error: TeiGeodataException.InvalidArgument) {
    println("invalid argument: ${error.message}")
}
Output
invalid argument: (91, 0) is not a point: the latitude is outside -90 to 90 degrees

Threads, coroutines and Android

Handles are thread-safe and AutoCloseable (use { } in Kotlin, try-with-resources in Java); a cleaner frees one you forget. The store's blocking calls have …Async forms returning CompletableFuture, which Kotlin awaits with kotlinx-coroutines-jdk8's await().

On Android, keep a bundled pack uncompressed (androidResources { noCompress += "tgd" }) and open it in place, without copying it out of the APK:

context.assets.openFd("world-np-lite.tgd").use { fd ->
    engine.openFileRange(context.applicationInfo.sourceDir, fd.startOffset, fd.length)
}

The whole program

Run it from a checkout of the repository, which builds what the language needs, fetches the pinned pack and compares the output:

cargo xtask docs-examples --fetch --check --lang kotlin

Next

  • Concepts: places and IDs, packs and components, results, the store.
  • Reference: every query, its columns and its errors.
  • Data: what each country's packs hold, with their sources and measured accuracy.

On this page