Go
teigeodata from Go, with cgo or without it (purego): offline geocoding with typed column reads and rows as maps.
The Go module calls the C library through cgo, or through
purego when built with CGO_ENABLED=0, so it cross-compiles
without a C toolchain. The library is loaded at run time: the file passed to LoadLibrary, then
the one TEIGEODATA_LIB names, then the release's prebuilt library in the user cache (checked
against the SHA-256 the module pins), then the system's.
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
go get github.com/teispace/teigeodata/bindings/goThe module's versions are the tags bindings/go/vX.Y.Z, made with each release. Go 1.26 or
later. Fetch the prebuilt library once (from the first
release that carries it):
go run github.com/teispace/teigeodata/bindings/go/cmd/teigeodata-fetchor build it from a checkout and name it:
cargo build --release -p teigeodata-ffi
export TEIGEODATA_LIB=$PWD/target/release/libteigeodata_ffi.so # .dylib on macOS, .dll on WindowsGet 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 # 243ae55509a538b1f61da50994a791cc78e7deb70bb4bf743b9f59d458cbe3f3An 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), read in place by NewReader. Records()
gives each row as a Record (a map[string]any, nil where null); the tour reads every
result through one helper:
// rows reads a result: every row as a Record (column name to value, nil where null).
func rows(blob []byte, err error) []tg.Record {
if err != nil {
log.Fatal(err)
}
r, err := tg.NewReader(blob)
if err != nil {
log.Fatal(err)
}
records, err := r.Records()
if err != nil {
log.Fatal(err)
}
return records
}
Typed column reads avoid the maps for large results: r.Strings("name"),
tg.Values[float64](r, "lat") (a slice viewing the blob, no copy), r.Nulls("elevation").
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.
engine, err := tg.NewEngine()
if err != nil {
log.Fatal(err)
}
defer engine.Close()
if _, err := engine.OpenFile(pack); err != nil {
log.Fatal(err)
}
fmt.Println("layers:", engine.Layers())layers: 1OpenBytesadds a pack from bytes already in memory (a download, an app asset, the browser).OpenFileRangeopens a pack stored uncompressed inside another file, such as an Android APK.- Each
…Withform takesOpenOptions: 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. OpenFilereturns the layer's number;Removetakes 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.
for _, p := range rows(engine.Search("Pokhara", 3)) {
fmt.Printf("%s %s %s %.4f, %.4f score %d\n",
p["id"], p["name"], p["kind"], p["lat"], p["lon"], p["score"])
}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 90The 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 (tg.LimitMax).
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.
for _, p := range rows(engine.Search("Kathmandu, Bagmati", 2)) {
fmt.Printf("%s %s %s %d\n", p["id"], p["name"], p["kind"], p["level"])
}tgd:np/2cn Kathmandu settlement 0
tgd:np/2gm Kathmandu admin 3The 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).
// Many places share a name; a focus (the user's location) ranks the near ones first.
lat, lon, scale := 28.7, 80.6, 30_000.0
options := &tg.SearchOptions{FocusLat: &lat, FocusLon: &lon, FocusScaleM: &scale}
for _, p := range rows(engine.SearchWith("Shivapur", 3, options)) {
fmt.Printf("%s %s %.4f, %.4f\n", p["id"], p["name"], p["lat"], p["lon"])
}tgd:np/2v99 Shivapur 28.5310, 80.8213
tgd:np/2raj Shivapur 28.7141, 80.9869
tgd:np/2rkx Shivapur 28.5061, 81.3032Set 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.
place := rows(engine.Get("tgd:np/1xhb"))[0]
fmt.Println(place["name"], place["kind"])
fmt.Printf("at %.6f, %.6f, %d m\n", place["lat"], place["lon"], place["elevation"])
fmt.Println("timezone", place["tz"], "parent", place["parent"])Pokhara settlement
at 28.266890, 83.968000, 1006 m
timezone Asia/Kathmandu parent tgd:np/1xnrelevation 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.
for _, p := range rows(engine.Ancestors("tgd:np/1xhb")) {
line := fmt.Sprintf("%s %d %s %s", p["kind"], p["level"], p["name"], orEmpty(p["iso"]))
fmt.Println(strings.TrimRight(line, " "))
}
children := rows(engine.Children("tgd:np/295c"))
fmt.Println("Kaski has", len(children), "children")admin 3 Pokhara
admin 2 Kaski
admin 1 Gandaki NP-P4
country 0 Nepal NP
Kaski has 5 childrenlevel 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").
for _, p := range rows(engine.Reverse(27.7172, 85.3240, 3)) {
fmt.Printf("%s %.0f m at %.0f°\n", p["name"], p["meters"], p["bearing"])
}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.
within := rows(engine.WithinRadius(27.7172, 85.3240, 500, 10))
fmt.Printf("%d places within 500 m; farthest %.0f m\n", len(within), within[len(within)-1]["meters"])3 places within 500 m; farthest 384 mFind places near a place
Nearby is reverse geocoding from a place you already have: the places nearest it,
itself left out.
for _, p := range rows(engine.Nearby("tgd:np/2cn", 3)) {
fmt.Printf("%s %.0f m\n", p["name"], p["meters"])
}Bhrikuti Mandap 168 m
Bagbazar 354 m
Shahidgate 393 mAdmin 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).
for _, p := range rows(engine.AdminAt(28.2096, 83.9856)) {
fmt.Println(strings.TrimRight(fmt.Sprintf("%d %s %s", p["level"], p["name"], orEmpty(p["iso"])), " "))
}
state := rows(engine.ByIso("NP-P4"))[0]
fmt.Println("NP-P4 is", state["name"], state["id"])0 Nepal NP
1 Gandaki NP-P4
2 Kaski
3 Pokhara
NP-P4 is Gandaki tgd:np/2922Boundaries 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.
zone := rows(engine.TzAt(27.7172, 85.3240))[0]["tz"].(string)
offset := rows(engine.TzOffsetAt(zone, 1_700_000_000))[0]
fmt.Println(zone, offset["seconds"], "s east of UTC,", offset["abbr"], "dst", offset["dst"])
local := rows(engine.TzLocal("America/New_York", 2026, 3, 8, 2, 30, 0))[0]
fmt.Println("02:30 on 2026-03-08 in New York:", local["kind"], local["before"], "->", local["after"])
fmt.Println("tzdb", engine.TzVersion())Asia/Kathmandu 20700 s east of UTC, +0545 dst 0
02:30 on 2026-03-08 in New York: gap -18000 -> -14400
tzdb 2026fTzVersion 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.
height := rows(engine.ElevationAt(27.7172, 85.3240))[0]
fmt.Printf("%.1f m above %s (%s, %.0f m grid)\n",
height["meters"], height["datum"], height["source"], height["resolution_m"])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.
meters, err := tg.DistanceM(27.7172, 85.3240, 28.2096, 83.9856)
if err != nil {
log.Fatal(err)
}
heading, err := tg.BearingDeg(27.7172, 85.3240, 28.2096, 83.9856)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Kathmandu to Pokhara: %.1f km, heading %.0f°\n", meters/1000, heading)
apart := rows(engine.Distance("tgd:np/2cn", "tgd:np/1xhb"))[0]
fmt.Printf("place to place: %.1f km at %.0f°\n", apart["meters"].(float64)/1000, apart["bearing"])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.
shape := rows(engine.Boundary("tgd:np/2gm", 0))[0]
geojson := shape["geojson"].(string) // a GeoJSON Feature, for any map library
var feature struct {
Geometry struct{ Type string } `json:"geometry"`
}
if err := json.Unmarshal([]byte(geojson), &feature); err != nil {
log.Fatal(err)
}
fmt.Printf("%s of %d vertices at level %d\n", feature.Geometry.Type, shape["vertices"], shape["lod"])
fmt.Printf("tolerance %.0f m, %d bytes of GeoJSON\n", shape["tolerance_m"], len(geojson))Polygon of 176 vertices at level 0
tolerance 0 m, 4362 bytes of GeoJSONThe 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.
lod0 is full resolution; 1 to 6 are coarser, each within itstolerance_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. lodabove 6 isInvalidArgument; a pack installed withoutboundariesisMissingComponent.- 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:
| Code | Meaning |
|---|---|
InvalidArgument | An argument is outside its range: a latitude of 91, a limit over 10,000, a malformed ID. |
MissingComponent | The query needs a component the pack was installed without (search on a pack installed without search). |
Corrupt | The bytes are not a valid pack, or a section does not match its hash. |
Io | A file could not be read. |
Network | No mirror answered, or the connection broke (the store only). |
Refused | The store refused: the catalog did not verify, a pack is not installed or another needs it. |
Cancelled | A callback or a job was asked to stop. |
Internal | A bug inside teigeodata; a panic never crosses into your program. |
A query that finds nothing is not an error: it returns no rows.
Every failure is a *tg.Error with a stable Code; match it with errors.As, or
errors.Is(err, tg.CodeMissingComponent):
_, err = engine.Reverse(91, 0, 1)
var failure *tg.Error
if errors.As(err, &failure) && failure.Code == tg.CodeInvalidArgument {
fmt.Println("invalid argument:", failure.Message)
}invalid argument: (91, 0) is not a point: the latitude is outside -90 to 90 degreesGoroutines
Handles may be used from any goroutine at once; Close frees one once no call holds it. The
store's long calls run as a Job whose progress you poll or wait for (WaitProgress) and which
Cancel stops.
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 go