How do you find nearby events with Geohash? From picking a point on Tencent Maps to querying neighboring cells in SQL

April 14, 2025

I wanted to build an Eventbrite-like WeChat mini program where people could discover nearby events and open posts to see what everyone was talking about. I had built the feed with Taro the day before. On the afternoon of April 14, 2025, I searched for “how to query coordinates efficiently in SQL.” The home page could sort posts by time, but if one event was across the street and another across town, how would the database know which to fetch first? That afternoon a MySQL article on geographic queries led me to Geohash. 1 How I built the mini program home page

The article described two different requirements. One was to find places within two kilometers of a coordinate. The other was to find the ten people closest to a user. The second example originally computed distance for every row in the table, sorted the results and took ten. The rewrite first used latitude and longitude bounds to select a rectangle, then calculated distance only for users inside it. Within minutes I was looking up geographic grids. Following the same idea, I could store a cell ID in advance for each event and select a few cells at query time. If a fixed box contains only three people, finding the nearest ten still requires searching farther out. Even after finding ten, you have to establish that nobody outside the box is closer than the tenth person. 1

How do China's offset map coordinates convert? How do WGS84, GCJ-02 and BD-09 differ?

The same café entrance has one pair of coordinates in WGS84, the system commonly used by GPS. Select it in Tencent Maps in mainland China and its GCJ-02 coordinates (nicknamed “Mars coordinates”) are offset from WGS84. Baidu's BD-09 applies another transformation on top of GCJ-02. This was the “encrypted coordinates” problem I was looking into. The place stays put, but the numbers for the same entrance change with the coordinate system. 23

Does picking a location on Tencent Maps already give GCJ-02 coordinates? Should I convert again?

They are already GCJ-02. Taro 4.0.10, the version I used, says Taro.chooseLocation() returns coordinates in the “gcj02 national surveying and mapping coordinate system.” If you store every event in GCJ-02, save the map selection directly. When a user refreshes “Nearby,” Taro.getLocation() returns WGS84 by default. Use Taro.getLocation({ type: 'gcj02' }) to obtain their position in the same system. Treating an existing GCJ-02 point as WGS84 and converting it again would introduce an error. 4

How do you convert between mainland maps' GCJ-02 and GPS's WGS84?

I first searched for “accuracy of phone latitude and longitude” and a few minutes later for “gridding GCJ-02 coordinates.” From articles on correcting map offsets I found Common Coordinate Systems and Projections by 才华横溢吴道简. I revisited it the next day. In the GCJ-02 section the author writes, “地图底图和矢量数据在使用之前,需要将坐标系进行统一。” The base map and vector data need a common coordinate system before use. 2

A CNBlogs article on conversion listed wandergis/coordtransform, and I opened the repository too. Below is the approximate algorithm from version 2.1.2 written as standalone JavaScript. Inputs and outputs use [longitude, latitude], in degrees. This version computes an offset only inside the rectangle 73.66 < longitude < 135.05 and 3.86 < latitude < 53.55. Points on or outside its bounds pass through unchanged. This is the library's range test, so bear the approximation in mind near national borders. 3

There are two steps. Polynomial and sine terms estimate the eastward and northward offsets in meters. The latitude of the input then gives the meters per degree of longitude and latitude. Dividing the offsets by those respective values gives angular differences to add to the coordinates.

function offsetDegrees(lon, lat) {
  if (lon <= 73.66 || lon >= 135.05 || lat <= 3.86 || lat >= 53.55) {
    return [0, 0];
  }

  const x = lon - 105;
  const y = lat - 35;
  const root = Math.sqrt(Math.abs(x));
  const wave = t => Math.sin(Math.PI * t);
  const common = 20 * (wave(6 * x) + wave(2 * x));

  const east = 300 + x + 2 * y + 0.1 * (x * x + x * y + root)
    + (2 / 3) * (common + 20 * wave(x) + 40 * wave(x / 3)
                        + 150 * wave(x / 12) + 300 * wave(x / 30));
  const north = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * root
    + (2 / 3) * (common + 20 * wave(y) + 40 * wave(y / 3)
                        + 160 * wave(y / 12) + 320 * wave(y / 30));

  const a = 6378245;                 // 这套公式采用的椭球长半轴,单位为米
  const e2 = 0.00669342162296594323; // 第一偏心率的平方
  const radiansPerDegree = Math.PI / 180;
  const phi = lat * radiansPerDegree;
  const q = 1 - e2 * Math.sin(phi) ** 2;
  const metersPerLonDegree = radiansPerDegree * a * Math.cos(phi) / Math.sqrt(q);
  const metersPerLatDegree = radiansPerDegree * a * (1 - e2) / q ** 1.5;
  return [east / metersPerLonDegree, north / metersPerLatDegree];
}

function wgs84ToGcj02(lon, lat) {
  const [dx, dy] = offsetDegrees(lon, lat);
  return [lon + dx, lat + dy];
}

function gcj02ToWgs84(lon, lat) {
  const [dx, dy] = offsetDegrees(lon, lat);
  return [lon - dx, lat - dy];
}

const mapPoint = wgs84ToGcj02(116.404, 39.915);
console.log(mapPoint);                  // 约 [116.410244, 39.916404]
console.log(gcj02ToWgs84(...mapPoint)); // 约 [116.404002, 39.915001]

Why does the sixth decimal place change on a round trip? The forward conversion evaluates the offset at the original GPS point. The reverse evaluates it at the already shifted map point. Since the coordinates fed into the formula differ, the amount subtracted differs slightly from the amount originally added. For Baidu inputs, first check whether you have BD-09 longitude and latitude. BD-09 adds another offset on top of GCJ-02. 3

Returning to nearby events, suppose phone location and map selection both pinpoint the same Beijing example. Here is how the two paths converge on a single cell.

flowchart TD
    gps["手机默认定位 · WGS84<br/>116.404000, 39.915000"]
    pin["腾讯地图选点 · GCJ-02"]
    gps -->|转换一次| aligned["同一地点的 GCJ-02 坐标<br/>116.410244, 39.916404"]
    pin -->|直接使用| aligned
    aligned -->|编码为 7 位 Geohash| cell["活动和用户落在同一格<br/>wx4g0fx"]

Without the conversion on the left, the phone coordinate encodes as wx4g0f6. The first six characters match the map selection, but the seventh differs. Querying only the user's seven-character cell could miss the event right in front of them.

How does “10,000 square meters per cell” differ from “a six-character code”?

My original request in Cursor was to enter a coordinate and a cell area in square meters and get the point's cell ID back. To divide a city into roughly 10,000-square-meter squares, the target side length is 100 meters. Choose an appropriate local metric projection, transform the coordinates into x, y in meters and compute the row and column from a fixed origin x0, y0. Here a cell includes its left and lower edges. Its right and upper edges belong to the next cells.

col = floor((x - x0) / 100)
row = floor((y - y0) / 100)

When I searched for “algorithms for dividing longitude and latitude into a grid,” one example rounded angular increments with round to assign a point to the nearest grid point. The formula above uses floor to determine which two boundaries contain the point. You can also make cells in degrees this way by substituting longitude, latitude and the corresponding angular increments for meters. The trade-off is that one degree of longitude covers less ground at higher latitudes. A Python example I actually opened uses area_to_grid to generate grid parameters, then passes those same parameters to GPS_to_grid. For IDs from two runs to be comparable, both need the same origin, increments and coordinate conventions. 5

For roughly fixed side lengths on the ground, first align the coordinates with the datum required by the projection. Then use a local projection such as UTM in the city's zone. Web Mercator, common in web base maps, also expresses coordinates in meters, but its scale varies with latitude. A width of 100 projected meters does not guarantee 100 meters on the ground. 6

Geohash takes a different input: you choose the precision first. Starting with the full ranges of longitude and latitude, bisect the longitude interval, record which half contains the point, then do the same for latitude. Subdivide them alternately and encode every five bits as one Base32 character. Adding a character divides the original rectangle into 32 smaller ones. This makes a common prefix handy for grouping events. The ground area of codes of equal length still varies with latitude. 7

I remember reading Learning GeoHash: An Explanation and Analysis of the Algorithm by 薯片要配干燥剂 during this research. The author gives an example at Beijing's Changying subway station: latitude 39.925746, longitude 116.599831, code wx4gjk32kfrx. Now “precision” becomes visible. Take the first six characters, wx4gjk, and the station is still inside, but the cell also holds more surrounding places. Chrome retained no record of my first read in April 2025. I reopened it on October 2 and November 17, 2026. 8

Why can querying only the current Geohash miss a shop across the street?

Imagine a street running exactly along the boundary between two cells. The user is on the west side and the café on the east. The points are only meters apart but belong to different cells. If the line also divides larger parent cells, even the beginnings of the codes may differ. Looking up only the user's cell ID or matching only its prefix will miss the event across the street. 7

The Zhihu article takes the current cell and its eight neighbors, then “分别计算这些点和自己的距离” (calculates the distance from the user to each point). The eight include the four diagonals. 8

On April 14 I asked Cursor a follow-up. 9

if i use geohash how to get the 1 degree and 2 degree connected blocks, use manhhatan distance( using 1 bnlock as unit) for degree

I wanted to count cells using Manhattan distance, taking each crossing of a shared edge as one step. Due east is one step. Northeast requires going east and then north, two steps. At a fixed code length, take the adjacent codes to the east, south, west and north, removing previously seen cells each time you expand a layer. 7

Manhattan distance from center cellCells in layerIn this layerTotal including center
0 stepsThe user's cell11
1 stepEast, west, south, north45
2 stepsFour cells two steps straight out, plus the four diagonals813

With those 13 IDs, the events table can store a cell_id of the same precision at write time, index the column and retrieve candidates in one SQL query with WHERE cell_id IN (...). The 13 cells answer precisely “within two edge crossings.”

Are nine cells enough to find events within a radius of the user?

Suppose every cell is a square 100 meters on a side and I stand one meter from my cell's eastern edge. Searching my cell and its eight neighbors reaches only 101 meters east of me. An event 130 meters due east should appear in a search for “within 140 meters,” but it lies in the second cell to the east. For “within 80 meters” the same nine cells cover the whole circle. Geohash cells' ground width and height depend on precision and latitude, so the actual query has to account for local dimensions.

The blue box encloses nine cells with sides of 100 meters. A circle with a radius of 140 meters centered on the user near a cell edge extends outside the box, covering an event 130 meters due east.

If the home page just needs to show events roughly in the neighborhood, nine cells are a simple start. To better approximate a circle around the user, keep the cell size and select all cells that intersect the desired circle at the user's actual position. Even if a cell's center lies outside the circle, a corner sticking into it might hold a qualifying event. Always expanding from nine to 25 cells reaches farther too, but the square's corners bring in more distant places.

If the interface explicitly says “within 140 meters,” you can first take all cells covered by the rectangle enclosing the circle and then compute each candidate's ground distance to the user, retaining only points at most 140 meters away. The same distance criterion applies at the center, edge or corner of a cell. Firebase's Geohash query example also takes these two steps: generate query ranges from center and radius, then filter by actual distance. 1011

What requirements would lead me to a different grid?

That afternoon, after reading the Python example mapping GPS points to cells, I opened Wuhan University Professor Zhu Xinyan's Framework Design and Related Technologies for a Multilevel Spatial Information Grid. The project uses cell centers as reference positions. Features in each cell need only store offsets from the center. Areas with sparse features use coarse cells, with further subdivision in cities. The project demonstrated this with population survey data from Hubei: a grid code could be used to aggregate population counts across multiple nodes. I was asking “who is near me?” Their example asks “how many people live in this area?” Both assign places to cell IDs, but the queries that follow differ considerably. 12

Looking back at several common algorithms, what matters most in choosing one is what computation follows once the ID is in the database.

What happens nextHow to divide the areaWhat to keep in mind
Group local events into a heat map, or meet an explicit requirement for roughly 100-meter squaresStore row and column in a regular grid. Subdividing by angle is simplest. For ground dimensions choose a suitable local projection.Fix the origin and increments. Reconsider the projection if you cross zones or extend coverage. 56
Store a key for grouping events by prefix and looking up neighborsGeohash encodes successively subdivided longitude/latitude rectangles as strings.Choose the precision, then enumerate cells to suit the application's definition of “nearby.” 7
Align remote-sensing or geographic data at different scalesGeoSOT expands the encoding ranges of degrees, minutes and seconds and recursively quarters the surface, aligning whole degrees, minutes and seconds with specific levels.It addresses a common grid for data from multiple sources and hierarchical retrieval. 13
Analyze foot traffic across adjacent areas, or cover a region with a set of global cellsH3 mostly uses hexagons and can retrieve neighbors within a given number of steps. S2 projects the six faces of a cube onto a sphere and recursively quarters each quadrilateral.H3 also has 12 pentagons at each level. Steps between neighbors cannot be read directly as ground meters. S2 can cover a target region with a combination of cells at different levels. 14

Back in career-partner, I had traced the question to “can we give each location a stable cell ID and retrieve events from first- and second-order neighbors?” The surviving home page displays mock posts in the feed, and the backend entry point is still an empty file. The prototype left me with a concrete query design. If the interface promises “a few blocks nearby,” I can define how many cell edges to cross. If it promises “within one kilometer,” I still owe the user a distance calculation.

References

Footnotes

  1. progressDabinge [dabinge1]. (n.d.). sql语句查询经纬度范围 [转载]. CSDN,两公里查询及后半部分的最近十人示例。 ↩ ↩2

  2. 酸奶小妹. (2014, March 27). 【地图API】为何您的坐标不准?如何纠偏? 博客园,第三节「坐标偏移」A、B 两项。当天打开的是阿里云开发者社区转载页。才华横溢吴道简. (2021, April 9). 常用坐标系及投影:WGS84、GCJ02、CGCS2000、BD09、Pseudo-Mercator、UTM、BD09MC. 知乎,「二、分项介绍」第 3 节「GCJ02坐标系」小结及第 8 节「UTM投影」。 ↩ ↩2

  3. stardsd. (2020, January 16). WGS84、GCJ02、BD09 坐标系之间的转换算法. 博客园,文首的仓库链接及转换函数。wandergis. (n.d.). coordtransform (2.1.2). 双向转换实现。代码和示意图沿用项目的北京示例点,输出按实算结果显示到小数点后六位。 ↩ ↩2 ↩3

  4. O2Team. (n.d.). @tarojs/taro 4.0.10,types/api/location/index.d.ts. npm. getLocation.Option.type(第 50–53 行)及 chooseLocation.SuccessCallbackResult(第 169–175 行)。 ↩

  5. weixin_51671794. (2020, December 7). 将经纬度网格化. CSDN,经纬度格点化代码。朗泰乐. (2024, April 12). 【GIS】经纬度坐标转网格坐标. CSDN,函数 tr2grid。 ↩ ↩2

  6. PROJ contributors. (n.d.). Universal Transverse Mercator (UTM)、Web Mercator / Pseudo Mercator. PROJ documentation. UTM 的适用分带,Web Mercator 的投影公式。 ↩ ↩2

  7. Veness, C. (n.d.). Geohash encoding/decoding. Movable Type Scripts. 编码长度、边界和邻格。Veness, C. (n.d.). latlon-geohash. GitHub,相邻方向与 neighbours 接口。 ↩ ↩2 ↩3 ↩4

  8. 薯片要配干燥剂. (2022, September 11 修订). GeoHash算法学习讲解、解析及原理分析. 知乎,“通过上面这张图”段及文末“2018年4月21日下午地铁上续更”的常营站算例。 ↩ ↩2

  9. Cai, B. (2025, April 14). Mapping GPS Coordinates to Block IDs. Cursor,career-partner 工作区,第 2 条用户提问。会话创建于北京时间 17:37:43。 ↩

  10. Firebase. (n.d.). Geo queries. Cloud Firestore documentation. Query Geohashes,小节中的 geohashQueryBounds 与 distanceBetween 示例。 ↩

  11. Oracle. (n.d.). Spatial convenience functions. MySQL 8.0 Reference Manual. ST_Distance_Sphere 的输入坐标和以米为单位的返回值。 ↩

  12. 朱欣焰教授课题组. (n.d.). 空间信息多级格网的框架设计与相关技术研究. 武汉大学测绘遥感信息工程国家重点实验室,重点项目展示,第 2 节及第 5 节成果(11)。项目原址,2020 年 6 月 24 日网页存档。 ↩

  13. 程承旗、吴飞龙、王嵘、秦永刚、童晓冲、陈波. (2016). 地球空间参考网格系统建设初探. 北京大学学报(自然科学版),52(6). GeoSOT 网格剖分方法及图 1。 ↩

  14. H3 contributors. (n.d.). Overview of the H3 geospatial indexing system、Grid traversal functions. H3 documentation. 全球剖分与五边形,gridDisk。S2 Geometry. (n.d.). S2 cells. S2 Developer Guide. 球面四边形与区域覆盖。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-04-14). How do you find nearby events with Geohash? From picking a point on Tencent Maps to querying neighboring cells in SQL. https://caiborui.com/blog/2025-04-14-zh-geohash-nearby-events-entrans

@misc{borui2025-5290045b,
  author = {borui},
  title = {{How do you find nearby events with Geohash? From picking a point on Tencent Maps to querying neighboring cells in SQL}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-04-14-zh-geohash-nearby-events-entrans}
}