Haversine distance and geo indexes
You can narrow nearby restaurant candidates with a bounding box, verify the circle with haversine distance, and keep distance-based pagination deterministic in W2O3.
Learning outcomes
- Convert a radius in kilometres into latitude and longitude ranges using the centre latitude.
- Explain why a bounding box is a candidate prefilter and why its corners need an exact distance check.
- Calculate haversine distance using an earth radius of 6371 km and return the result in integer metres.
- Understand how the
(is_active, lat, lng)composite index supports geographic filtering and how to inspect its use withEXPLAIN. - Keep distance-based pagination deterministic by ordering and continuing with the pair
(distance_m, id).
A request for restaurants within 5 km of the test centre at 13.0827, 80.2707 must exclude a restaurant placed 3.6 km north and 3.6 km east. That restaurant is inside a rectangular geographic prefilter, but its actual distance is about 5.1 km. W2O3 adds sort=distance to the restaurant list, so you need an exact circular check and a stable way to paginate results at equal distances.
Geographic coordinates and bounding boxes
Latitude and longitude describe positions on the Earth's surface in degrees. One degree of latitude is approximately 111.195 kilometres. The distance represented by one degree of longitude depends on latitude because meridians get closer together towards the poles.
At latitude 13.0827, one degree of longitude represents approximately 111.195 * cos(13.0827) kilometres. Use the centre latitude when converting a requested radius into longitude degrees.
A Bounding box is a rectangle around the search centre. It gives MySQL coordinate ranges that can narrow the candidate restaurants before you calculate their exact distances.
For a radius in kilometres, calculate the half-widths as follows:
const kmPerDegree = 111.195
latHalfWidth := radiusKm / kmPerDegree
cosLat := math.Cos(latitude * math.Pi / 180)
lngHalfWidth := radiusKm / (kmPerDegree * cosLat)Use those half-widths to calculate the minimum and maximum latitude and longitude. Clamp latitude to its valid range. Geographic bounds also need to account for longitude wrapping near the antimeridian.
The important property is that the rectangle must contain every point inside the requested circle. It can contain extra points. It must not exclude a valid restaurant before the exact distance check.
The circular distance check
A bounding box is not the requested radius. Its corners can be farther from the search centre than the radius itself.
In the W2O3 fixture, a restaurant 3.6 km north and 3.6 km east lies inside the 5 km bounding box. Its straight-line distance is approximately:
sqrt(3.6 * 3.6 + 3.6 * 3.6) = 5.09 kmIt must not appear in the results. The bounding box reduces the candidate set, but an exact distance calculation decides whether each candidate qualifies.
Haversine distance
The Haversine distance calculates the great-circle distance between two points on a spherical Earth. It converts latitude and longitude differences into radians, calculates the central angle between the points, then multiplies that angle by the Earth's radius.
For this exercise, use an earth radius of 6371 kilometres:
func HaversineKm(lat1, lng1, lat2, lng2 float64) float64 {
const earthRadiusKm = 6371.0
rad := math.Pi / 180
phi1, phi2 := lat1*rad, lat2*rad
dPhi := (lat2 - lat1) * rad
dLambda := (lng2 - lng1) * rad
a := math.Pow(math.Sin(dPhi/2), 2) +
math.Cos(phi1)*math.Cos(phi2)*
math.Pow(math.Sin(dLambda/2), 2)
a = math.Max(0, math.Min(1, a))
return 2 * earthRadiusKm * math.Asin(math.Sqrt(a))
}The function returns kilometres. Convert that value to metres and round it to an integer:
distanceM := int64(math.Round(HaversineKm(
centreLat, centreLng, restaurantLat, restaurantLng,
) * 1000))The SQL calculation must use 6371000 metres, which is the same earth radius expressed in metres. Both calculations need to use the same haversine formula. W2O3 checks that each returned distance_m agrees with the expected haversine distance within 2 metres.
The calculation assumes a spherical Earth. The exercise checks this model with the specified radius, not a more detailed ellipsoidal geodesic calculation.
Indexing the geographic prefilter
The database needs an efficient way to find active restaurants inside the coordinate ranges. A Composite index on restaurants can support that prefilter.
For this exercise, migration 0004 adds this index:
ALTER TABLE restaurants
ADD INDEX idx_rest_active_geo (is_active, lat, lng);The column order follows the query conditions. The query checks is_active = 1, then applies ranges to lat and lng.
A B+tree index stores its columns in order. MySQL can use the leading columns according to the Leftmost-prefix rule rule. The equality condition on is_active narrows the leading part of the index, and the latitude range narrows the range scan that follows.
There is an important limitation: after MySQL encounters a range condition on lat, the lng condition generally cannot further narrow that same index range scan. But lng is still present in the index entries. MySQL can evaluate the longitude condition from those entries through index condition pushdown, potentially avoiding table-row reads for candidates outside the longitude range.
An InnoDB Secondary index stores the indexed columns along with the primary key reference. Including the geographic columns makes them available while MySQL evaluates the prefilter.
The index does not guarantee that MySQL will choose it. The optimizer considers table statistics and estimated query costs. Use EXPLAIN to inspect the actual plan.
EXPLAIN
SELECT id, name, lat, lng
FROM restaurants
WHERE is_active = 1
AND lat BETWEEN 13.03 AND 13.13
AND lng BETWEEN 80.22 AND 80.33;Check the selected key, access type and estimated rows. The distance query in W2O3 must have a usable index on restaurants. A migration that creates an index is not enough if the query cannot use an index.
Distance ordering and pagination
After the database narrows the candidates, calculate the distance, keep only restaurants inside the circle, and order the results. The distance must be rounded to integer metres before you use it for ordering or pagination.
The order has two parts:
ORDER BY dist_m, idThe distance puts nearer restaurants first. The ID breaks ties when two restaurants have the same rounded distance.
This tie-breaker matters when a page ends between two restaurants at the same distance. A cursor containing only the distance cannot identify which tied restaurant the previous page ended on. The next page could repeat a restaurant or skip one.
Use both values as the pagination position:
(distance_m, id)The next query continues after that pair:
WHERE dist_m > after_dist
OR (dist_m = after_dist AND id > after_id)
ORDER BY dist_m, idThe comparison and ordering must use the same rounded integer distance. Comparing unrounded floating-point distances can produce unreliable equality checks at page boundaries.
For example, suppose two restaurants both have distance_m = 2500. If the first has ID 41 and the second has ID 52, the order is:
(2500, 41)
(2500, 52)After returning the first restaurant, the next page continues after (2500, 41) and can return (2500, 52).
Keep the resulting next_cursor opaque to clients. The client returns it unchanged. The server owns its representation and validates it before using the pagination position.
Fetch one extra row beyond the requested page size to determine whether another page exists. If there is another page, create the next cursor from the last row actually returned, not from the extra row.
Common implementation mistakes
A second mistake is calculating distance in SQL with a different earth radius from the one used in Go. The returned distance_m then disagrees with the expected value. Keep the radius at 6371 km in Go and 6371000 metres in SQL.
Another mistake is paginating on distance alone. It can pass when every distance is different, then fail when a page boundary splits equal-distance results. Use the ID as the second ordering and cursor value. W2O3 checks this at page limits from 1 through 4.
Distance search in the restaurant API
The optional exercise GET /v1/restaurants: sort by distance adds distance ordering to the existing restaurant list. The request around Chennai uses lat=13.0827, lng=80.2707 and radius_km=5. Each returned item includes distance_m, and the page order is nearest first with ascending ID breaking ties.
The geographic index belongs in migration 0004. The query must use an index on restaurants, while the exact distance check decides which candidates are inside the circle. Keep the rounded distance and ID together when continuing a page.
Check your understanding
A customer requests restaurants within 5 km. A restaurant is inside the bounding box but is 5.1 km from the centre. What should the API do?
References
Everything above is explained on this page; these are where it comes from (MySQL 8.4, Go 1.27).