geohash

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 5, 2026 License: Apache-2.0 Imports: 2 Imported by: 0

Documentation

Overview

Package geohash 提供经纬度的 Geohash 编码/解码、邻居计算与覆盖查询,纯标准库。

Geohash 把二维经纬度编码成一个 base32 字符串:前缀相同的两点在地理上相邻, 前缀越长精度越高。因此"附近的人/店铺/开播"可退化为**字符串前缀匹配**—— 在 Redis/DB 里按 geohash 前缀建索引即可范围检索,无需专门的空间数据库。

与 pkg/spatial 的区别(互补):

  • spatial 是平面网格索引(float64 x/y),适合游戏地图这类"局部平面坐标";
  • geohash 面向真实地球经纬度(WGS84),适合 LBS——编码后可直接用字符串前缀 跨进程/落库检索,不必把全部实体加载进内存。

精度参考(geohash 长度 → 单元约尺寸):

4 → ~39km,5 → ~4.9km,6 → ~1.2km,7 → ~153m,8 → ~38m,9 → ~4.8m。

边界说明:Geohash 的"同前缀=相邻"在单元边界处有裂缝——两个物理相邻的点可能 落在不同前缀。做邻近搜索时应取中心单元 + 其 8 个邻居一起查(见 Neighbors/ CoverNeighbors),再对候选做精确距离过滤。

纯函数,无状态,并发安全。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CoverNeighbors

func CoverNeighbors(lat, lng float64, precision int) []string

CoverNeighbors 返回中心单元 + 其 8 个邻居共 9 个 Geohash(去重), 用作邻近搜索的候选前缀集合:先按这些前缀检索,再对结果做精确距离过滤。

func DecodeCenter

func DecodeCenter(hash string) (lat, lng float64)

DecodeCenter 解码并返回单元中心点坐标(便捷封装)。

func Distance

func Distance(lat1, lng1, lat2, lng2 float64) float64

Distance 返回两点间的大圆距离(米),Haversine 公式。用于候选集的精确过滤/排序。

func Encode

func Encode(lat, lng float64, precision int) string

Encode 把经纬度编码为长度 precision 的 Geohash 字符串。 precision 建议 1..12;<=0 视为 12,>12 截断为 12。

func Neighbor

func Neighbor(hash string, dLat, dLng int) string

Neighbor 返回 hash 在指定方向上的相邻单元(同长度)。 dLat/dLng 取 -1/0/1:如 (1,0)=北,(0,1)=东,(1,1)=东北。(0,0) 返回自身。

func Neighbors

func Neighbors(hash string) []string

Neighbors 返回 hash 周围 8 个方向的邻居(不含自身),顺序: N, NE, E, SE, S, SW, W, NW。用于覆盖 Geohash 边界裂缝的邻近搜索。

Types

type Box

type Box struct {
	MinLat, MaxLat float64
	MinLng, MaxLng float64
}

Box 是一个 Geohash 单元覆盖的经纬度范围(边界框)。

func Decode

func Decode(hash string) Box

Decode 把 Geohash 字符串解码为其覆盖的边界框。 非法字符会被忽略(按已解析部分返回);空串返回整个世界范围。

func (Box) Center

func (b Box) Center() (lat, lng float64)

Center 返回边界框中心点。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL