// Package places finds regions by place name, offline, with the same list of // cities the browser uses (GeoNames, CC BY 4.0; see web/scripts/places.mjs). // // A region is a 3-character geohash cell, about 100 to 150 km wide: right for // the network, meaningless to a person. "Bonn" or "Cologne" is turned into the // cell it lies in plus any other cell within a few dozen kilometres, so a city // near a cell's edge does not miss the listings just across it. package places import ( "bufio" "io/fs" "math" "slices" "sort" "strconv" "strings" "unicode" "golang.org/x/text/unicode/norm" ) // File is the list's name in the embedded UI. const File = "places.tsv" // Place is a city. type Place struct { Name string Lat, Lon float64 Country string // ISO code Population int Alts []string // other names (Köln: Cologne) keys []string // folded: the name, the alternatives, then the ASCII spelling } // Match is a place that fits a query. type Match struct { Place *Place // Matched is the name that fit, when it is not the place's main name. Matched string score int } // Fold lower-cases and strips accents, with ß as ss: "Zürich", "zurich" and // "ZÜRICH" are one key. func Fold(s string) string { s = strings.ReplaceAll(s, "ß", "ss") var b strings.Builder for _, r := range norm.NFD.String(s) { if unicode.Is(unicode.Mn, r) { continue } b.WriteRune(unicode.ToLower(r)) } return b.String() } // unTranslit undoes how a keyboard without umlauts writes them: // "muenchen" becomes "munchen", which is what Fold makes of "München". func unTranslit(s string) string { return strings.NewReplacer("ae", "a", "oe", "o", "ue", "u").Replace(s) } // Load reads the list from fsys (the embedded UI): name, ASCII name, latitude, // longitude, country, population, alternatives, tab-separated. func Load(fsys fs.FS) ([]Place, error) { f, err := fsys.Open(File) if err != nil { return nil, err } defer f.Close() var out []Place sc := bufio.NewScanner(f) sc.Buffer(make([]byte, 0, 64<<10), 1<<20) for sc.Scan() { cols := strings.Split(sc.Text(), "\t") if len(cols) < 6 { continue } lat, err1 := strconv.ParseFloat(cols[2], 64) lon, err2 := strconv.ParseFloat(cols[3], 64) if cols[0] == "" || err1 != nil || err2 != nil { continue } pop, _ := strconv.Atoi(cols[5]) p := Place{Name: cols[0], Lat: lat, Lon: lon, Country: cols[4], Population: pop} if len(cols) > 6 && cols[6] != "" { p.Alts = strings.Split(cols[6], "|") } p.keys = append(p.keys, Fold(p.Name)) for _, a := range p.Alts { p.keys = append(p.keys, Fold(a)) } if cols[1] != "" { p.keys = append(p.keys, Fold(cols[1])) // "Koeln": found, but shown as "Köln" } out = append(out, p) } return out, sc.Err() } func score(key, q string) int { switch { case key == q: return 0 case strings.HasPrefix(key, q): return 1 case slices.ContainsFunc(strings.FieldsFunc(key, func(r rune) bool { return r == ' ' || r == '-' }), func(w string) bool { return strings.HasPrefix(w, q) }): return 2 case len(q) >= 3 && strings.Contains(key, q): return 3 } return 4 } // Search returns the best matches for query: exact names first, then by size. func Search(places []Place, query string, limit int) []Match { q1 := Fold(strings.TrimSpace(query)) if len([]rune(q1)) < 2 { return nil } qs := []string{q1} if q2 := unTranslit(q1); q2 != q1 { qs = append(qs, q2) } var hits []Match for i := range places { p := &places[i] best, bestKey := 4, 0 for k, key := range p.keys { for _, q := range qs { if s := score(key, q); s < best { best, bestKey = s, k } } } if best == 4 { continue } m := Match{Place: p, score: best} // Keys after the alternatives are the ASCII spelling of the main name. if bestKey >= 1 && bestKey <= len(p.Alts) { m.Matched = p.Alts[bestKey-1] } hits = append(hits, m) } sort.SliceStable(hits, func(i, j int) bool { if hits[i].score != hits[j].score { return hits[i].score < hits[j].score } return hits[i].Place.Population > hits[j].Place.Population }) if len(hits) > limit { hits = hits[:limit] } return hits } const base32 = "0123456789bcdefghjkmnpqrstuvwxyz" // Encode is the geohash of a position, precision characters long. func Encode(lat, lon float64, precision int) string { latR, lonR := [2]float64{-90, 90}, [2]float64{-180, 180} var out []byte bits, value := 0, 0 even := true for len(out) < precision { r, x := &latR, lat if even { r, x = &lonR, lon } mid := (r[0] + r[1]) / 2 value <<= 1 if x >= mid { value |= 1 r[0] = mid } else { r[1] = mid } even = !even if bits++; bits == 5 { out = append(out, base32[value]) bits, value = 0, 0 } } return string(out) } // RegionPrecision is the length of a region's geohash. const RegionPrecision = 3 const kmPerDegree = 111.2 // CellsNear returns the regions to follow for a position: the cell it lies in // first, then any other cell within about km of it. func CellsNear(lat, lon, km float64) []string { cell := func(la, lo float64) string { la = math.Max(-89.999, math.Min(89.999, la)) lo = math.Mod(math.Mod(lo+180, 360)+360, 360) - 180 return Encode(la, lo, RegionPrecision) } out := []string{cell(lat, lon)} dLat := 1 / kmPerDegree dLon := 1 / (kmPerDegree * math.Max(0.05, math.Cos(lat*math.Pi/180))) // Two rings (half and full distance) in 16 directions: a cell clipping the // circle anywhere is hit by one of them. for _, r := range []float64{km / 2, km} { for i := 0; i < 16; i++ { a := float64(i) / 16 * 2 * math.Pi c := cell(lat+math.Sin(a)*r*dLat, lon+math.Cos(a)*r*dLon) if !slices.Contains(out, c) { out = append(out, c) } } } return out }