MCPcopy Create free account
hub / github.com/NodeDB-Lab/nodedb / geohash_encode

Function geohash_encode

nodedb-spatial/src/geohash.rs:47–97  ·  view source on GitHub ↗

Encode a (longitude, latitude) coordinate to a geohash string. - `precision`: number of characters (1–12). Default 6 gives ~1.2 km cells. - Longitude range: [-180, 180] - Latitude range: [-90, 90] Returns an empty string if precision is 0.

(lng: f64, lat: f64, precision: u8)

Source from the content-addressed store, hash-verified

45///
46/// Returns an empty string if precision is 0.
47pub fn geohash_encode(lng: f64, lat: f64, precision: u8) -> String {
48 let precision = precision.min(12) as usize;
49 if precision == 0 {
50 return String::new();
51 }
52
53 let mut min_lng = -180.0_f64;
54 let mut max_lng = 180.0_f64;
55 let mut min_lat = -90.0_f64;
56 let mut max_lat = 90.0_f64;
57
58 let mut result = String::with_capacity(precision);
59 let mut bits: u8 = 0;
60 let mut bit_count: u8 = 0;
61 let mut is_lng = true; // Longitude first (even bits).
62
63 // Each character encodes 5 bits. Total bits = precision * 5.
64 let total_bits = precision * 5;
65
66 for _ in 0..total_bits {
67 if is_lng {
68 let mid = (min_lng + max_lng) / 2.0;
69 if lng >= mid {
70 bits = (bits << 1) | 1;
71 min_lng = mid;
72 } else {
73 bits <<= 1;
74 max_lng = mid;
75 }
76 } else {
77 let mid = (min_lat + max_lat) / 2.0;
78 if lat >= mid {
79 bits = (bits << 1) | 1;
80 min_lat = mid;
81 } else {
82 bits <<= 1;
83 max_lat = mid;
84 }
85 }
86 is_lng = !is_lng;
87 bit_count += 1;
88
89 if bit_count == 5 {
90 result.push(BASE32[bits as usize] as char);
91 bits = 0;
92 bit_count = 0;
93 }
94 }
95
96 result
97}
98
99/// Decode a geohash string to its bounding box.
100///

Callers 15

geohash_neighborFunction · 0.85
geohash_coverFunction · 0.85
encode_decode_roundtripFunction · 0.85
encode_precision_1Function · 0.85
encode_precision_12Function · 0.85
decode_centerFunction · 0.85
neighbor_northFunction · 0.85
neighbor_southFunction · 0.85
all_8_neighborsFunction · 0.85

Calls 1

pushMethod · 0.45

Tested by 13

encode_decode_roundtripFunction · 0.68
encode_precision_1Function · 0.68
encode_precision_12Function · 0.68
decode_centerFunction · 0.68
neighbor_northFunction · 0.68
neighbor_southFunction · 0.68
all_8_neighborsFunction · 0.68
neighbor_wraps_longitudeFunction · 0.68
encode_extremesFunction · 0.68