Geographic Math¶
3 endpoints for spatial calculations: multi-point distance, geographic bounding boxes, and centroid computation.
| Endpoint | Purpose |
|---|---|
POST /v1/geo/distance |
Distance along a chain of two or more lat/lon points |
POST /v1/geo/bounding-box |
Bounding box from a center point and radius |
POST /v1/geo/center |
Geographic centroid of multiple coordinates |
REST API Examples¶
Calculate distance between two cities¶
curl -X POST "https://geo.toolkitapi.io/v1/geo/distance" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"points": [{"lat": 51.5074, "lon": -0.1278}, {"lat": 48.8566, "lon": 2.3522}], "unit": "km"}'
const resp = await fetch("https://geo.toolkitapi.io/v1/geo/distance", {
method: "POST",
headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
body: JSON.stringify({
points: [{ lat: 51.5074, lon: -0.1278 }, { lat: 48.8566, lon: 2.3522 }],
unit: "km",
}),
});
const data = await resp.json();
console.log(`${data.total_distance} ${data.unit} via ${data.method}`);
console.log(`legs: ${data.legs.length}`);
Response
{
"total_distance": 343.557,
"unit": "km",
"method": "haversine",
"legs": [
{
"from_point": { "lat": 51.5074, "lon": -0.1278 },
"to_point": { "lat": 48.8566, "lon": 2.3522 },
"distance": 343.557
}
]
}
There is no miles field — request unit="mi" to get miles, or convert yourself. Per-leg results come back under legs (not segments).
Calculate bounding box¶
The center point is a nested object under center:
curl -X POST "https://geo.toolkitapi.io/v1/geo/bounding-box" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"center": {"lat": 51.5074, "lon": -0.1278}, "radius": 10, "unit": "km"}'
Find geographic centroid¶
curl -X POST "https://geo.toolkitapi.io/v1/geo/center" \
-H "X-API-Key: YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{"points": [{"lat": 51.5074, "lon": -0.1278}, {"lat": 48.8566, "lon": 2.3522}, {"lat": 52.5200, "lon": 13.4050}]}'
Python SDK Examples¶
Calculate distance between two cities¶
distance accepts a list of {"lat": float, "lon": float} points (minimum 2) and returns the total distance plus per-leg breakdown.
from toolkitapi import Geo
with Geo(api_key="tk_...") as geo:
result = geo.distance(
points=[
{"lat": 51.5074, "lon": -0.1278}, # London
{"lat": 48.8566, "lon": 2.3522}, # Paris
],
unit="km",
)
print(result["total_distance"]) # ~343.557
print(result["unit"]) # "km"
print(result["method"]) # "haversine"
Multi-leg route distance¶
Pass more than 2 points to calculate a route with per-leg distances:
from toolkitapi import Geo
# A → B → C → D road trip
route = [
{"lat": 40.7128, "lon": -74.0060}, # New York
{"lat": 41.8781, "lon": -87.6298}, # Chicago
{"lat": 39.7392, "lon": -104.9903}, # Denver
{"lat": 34.0522, "lon": -118.2437}, # Los Angeles
]
with Geo(api_key="tk_...") as geo:
result = geo.distance(route, unit="mi")
print(f"Total distance: {result['total_distance']} mi")
for i, leg in enumerate(result["legs"], start=1):
print(f" Leg {i}: {leg['distance']} mi")
Vincenty vs Haversine¶
Haversine is the default and works well for most applications. Use Vincenty for higher accuracy with antipodal or very short distances:
from toolkitapi import Geo
points = [
{"lat": -33.8688, "lon": 151.2093}, # Sydney
{"lat": 51.5074, "lon": -0.1278}, # London
]
with Geo(api_key="tk_...") as geo:
haversine = geo.distance(points, unit="km", method="haversine")
vincenty = geo.distance(points, unit="km", method="vincenty")
print(f"Haversine: {haversine['total_distance']} km")
print(f"Vincenty: {vincenty['total_distance']} km")
Calculate a bounding box¶
bounding_box is useful for database queries ("find all records within X km of this point") — pass a center coordinate and radius to get min_lat, max_lat, min_lon, max_lon.
from toolkitapi import Geo
with Geo(api_key="tk_...") as geo:
bbox = geo.bounding_box(
lat=51.5074, # London
lon=-0.1278,
radius=50,
unit="km",
)
print(bbox["min_lat"]) # ~51.417
print(bbox["max_lat"]) # ~51.597
print(bbox["min_lon"]) # ~-0.272
print(bbox["max_lon"]) # ~0.017
# Use with a database query:
# SELECT * FROM locations
# WHERE lat BETWEEN %(min_lat)s AND %(max_lat)s
# AND lon BETWEEN %(min_lon)s AND %(max_lon)s
Filter records near a location¶
from toolkitapi import Geo
shops = [
{"name": "Central Store", "lat": 51.5100, "lon": -0.1200},
{"name": "East Branch", "lat": 51.5200, "lon": 0.0100},
{"name": "North Outpost", "lat": 51.7000, "lon": -0.1500},
]
with Geo(api_key="tk_...") as geo:
bbox = geo.bounding_box(lat=51.5074, lon=-0.1278, radius=10, unit="km")
nearby = [
s for s in shops
if bbox["min_lat"] <= s["lat"] <= bbox["max_lat"]
and bbox["min_lon"] <= s["lon"] <= bbox["max_lon"]
]
print([s["name"] for s in nearby])
# ["Central Store", "East Branch"]
Find the geographic center of a set of points¶
center computes the true geographic centroid (using Cartesian averaging to handle the anti-meridian correctly):
from toolkitapi import Geo
# Find the center of a fleet of delivery vehicles
vehicles = [
{"lat": 51.5100, "lon": -0.1200},
{"lat": 51.4900, "lon": -0.1500},
{"lat": 51.5300, "lon": -0.0900},
{"lat": 51.5050, "lon": -0.1350},
]
with Geo(api_key="tk_...") as geo:
result = geo.center(vehicles)
print(result["center"]["lat"]) # ~51.5088
print(result["center"]["lon"]) # ~-0.1238
print(result["point_count"]) # 4
Center + bounding box together¶
A common pattern: find the centroid of a set of points and draw a bounding box around it:
from toolkitapi import Geo
locations = [
{"lat": 52.3676, "lon": 4.9041}, # Amsterdam
{"lat": 50.8503, "lon": 4.3517}, # Brussels
{"lat": 51.5074, "lon": -0.1278}, # London
{"lat": 48.8566, "lon": 2.3522}, # Paris
]
with Geo(api_key="tk_...") as geo:
centroid = geo.center(locations)
lat = centroid["center"]["lat"]
lon = centroid["center"]["lon"]
# 250 km box around the centroid
bbox = geo.bounding_box(lat=lat, lon=lon, radius=250, unit="km")
print(f"Center: {lat:.4f}, {lon:.4f}")
print(f"Bounding box: {bbox['min_lat']:.3f} to {bbox['max_lat']:.3f} lat")
Response Fields¶
distance response:
| Field | Type | Description |
|---|---|---|
total_distance |
float | Sum of all leg distances |
unit |
string | Distance unit (km, mi, m, nm) |
method |
string | haversine or vincenty |
legs |
list | Per-leg breakdown with from_point, to_point, distance |
bounding-box response:
| Field | Type | Description |
|---|---|---|
min_lat |
float | Southern boundary |
max_lat |
float | Northern boundary |
min_lon |
float | Western boundary |
max_lon |
float | Eastern boundary |
center |
object | Input center point {lat, lon} |
radius |
float | Input radius |
unit |
string | km or mi |
center response:
| Field | Type | Description |
|---|---|---|
center |
object | Computed centroid {lat, lon} (6 decimal places) |
point_count |
int | Number of input points averaged |
Error cases¶
| Status | When | Detail |
|---|---|---|
401 / 403 |
Missing or invalid X-API-Key |
{"detail": "Invalid API key"} |
422 |
points has fewer than 2 entries |
body.points — ensure this value has at least 2 items |
422 |
lat outside −90…90 or lon outside −180…180 |
body.points.N.lat — value must be within range |
422 |
Unknown unit / method |
Allowed: unit km/mi/m/nm, method haversine/vincenty |
422 |
bounding-box sent flat lat/lon instead of {"center": {...}} |
Missing body.center |
422 |
radius outside (0, 20000] |
must be greater than 0 / must be ≤ 20000 |
422 |
bounding-box unit is m or nm |
Only km and mi are accepted for radius |
Tips¶
bounding-boxtakes a nestedcenter. This differs fromdistanceandcenter, which takepoints. Sending flatlat/lonis the most common 422 on this toolkit.- Radius caps at 20,000 and rejects
m/nm(onlykm/mi), unlikedistance, which accepts all four units. distanceneeds at least 2 points. A single point returns422; two identical points return0.0.- Units are case-sensitive literals.
kilometers,KM, ormileswill all 422. - Vincenty can fail near antipodes — for nearly opposite points, haversine is the safer choice.
centeruses Cartesian (3D vector) averaging, so it stays correct across the anti-meridian where naive lat/lon averaging breaks.centerandbounding-boxround coordinates to 6 decimals (~11 cm precision).
Tip
Use bounding_box to quickly filter candidate rows from a database before running more expensive exact distance checks. The box overcounts slightly (it's a rectangle, not a circle), but it's fast to query with indexed lat/lon columns.
Implementation notes: how the numbers are produced¶
Everything below is observable behaviour of the live endpoints, derived from apis/geo/app/routers/math.py. Useful when a distance comes back a few metres off what your GIS library says.
Earth model and constants¶
The service treats Earth as a perfect sphere with mean radius 6371.0088 km (IUGG mean radius) — not a WGS84 ellipsoid. Consequences:
- Distances are accurate to roughly ±0.3 % versus ellipsoidal (Vincenty/Karney) results.
- A London→Paris great-circle distance comes out near 343.6 km; ellipsoidal implementations typically return ~343.5 km. Differences grow with distance (10,000 km routes can differ by tens of kilometres).
- If you need survey-grade accuracy, use your own geodesy library — these endpoints are built for ranking, bundling, and filtering, not legal or navigation boundaries.
Unit conversion factors¶
distance computes in kilometres internally, then multiplies by one constant:
unit |
Multiplier applied to km | Defined as |
|---|---|---|
km |
1.0 |
— |
mi |
0.621371198... |
3958.7613 / 6371.0088 |
m |
1000.0 |
— |
nm |
0.539956803... |
1 / 1.852 (1 nmi = 1.852 km exactly) |
These are exact ratios, not rounded approximations, so {"unit":"nm"} never drifts from the international nautical-mile definition.
bounding-box only converts mi → km (and back for output) using the same ratio. It never touches m or nm, hence the 422 noted above.
Haversine vs. Vincenty¶
Both methods run on the same spherical model; the difference is numerical conditioning, not the Earth model.
| Method | Formula | Behaviour |
|---|---|---|
haversine (default) |
2R·asin(√a) |
Stable everywhere. asin saturates gracefully, so antipodal points return ~20,015 km instead of NaN. |
vincenty |
R·atan2(√(a+b), c) |
The spherical Vincenty special case using atan2, not the full ellipsoidal iteration. Slightly better conditioned for very short legs (< 1 m), where Haversine's √a underflows. |
Neither method converges iteratively, so both are O(1) per leg — the cost of a 500-point route is linear in the number of legs.
import requests
BASE = "https://geo.toolkitapi.io/v1"
HEADERS = {"X-API-Key": "YOUR_KEY"}
def route_legs(points: list[dict], unit="km") -> list[float]:
"""Return each leg distance separately, for per-segment reporting."""
r = requests.post(
f"{BASE}/geo/distance",
headers=HEADERS,
json={"points": points, "unit": unit, "method": "haversine"},
timeout=10,
)
r.raise_for_status()
return [leg["distance"] for leg in r.json()["legs"]]
# Three-stop delivery run
stops = [
{"lat": 51.5074, "lon": -0.1278}, # London
{"lat": 52.4862, "lon": -1.8904}, # Birmingham
{"lat": 53.4808, "lon": -2.2426}, # Manchester
]
for i, d in enumerate(route_legs(stops), start=1):
print(f"Leg {i}: {d:.2f} km")
// Sum legs client-side and flag any leg over a threshold
const res = await fetch("https://geo.toolkitapi.io/v1/geo/distance", {
method: "POST",
headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
body: JSON.stringify({
points: [
{ lat: 51.5074, lon: -0.1278 },
{ lat: 52.4862, lon: -1.8904 },
{ lat: 53.4808, lon: -2.2426 },
],
unit: "mi",
method: "haversine",
}),
});
const { legs, total_distance, unit } = await res.json();
console.log(`Total: ${total_distance.toFixed(1)} ${unit} over ${legs.length} legs`);
const longLegs = legs.filter((l) => l.distance > 100);
if (longLegs.length) console.warn(`${longLegs.length} leg(s) exceed 100 ${unit}`);
Bounding-box geometry¶
Given radius_km and a centre at latitude φ, the router computes:
angular_radius = radius_km / 6371.0088 (radians)
min_lat = φ - angular_radius
max_lat = φ + angular_radius
Δlon = asin( sin(angular_radius) / cos(φ) ) ← widens with latitude
min_lon = λ - Δlon ; max_lon = λ + Δlon
Three behaviours fall out of that:
- The box grows east–west as you approach the poles. A 10 km radius at 60° N spans ~2× the longitude of the same radius at the equator. This is correct great-circle behaviour — a naive
Δlon = radius / cos(φ)approximation under-shoots. - Longitudes wrap, they don't clamp. A box centred at 179.9° E produces a
min_lonnear-179.x, i.e. legitimately spanning the anti-meridian. Do not assumemin_lon < max_lonin your SQLBETWEEN; use an OR-clause. - Polar caps are special-cased. If the radius reaches a pole (
|φ| + angular_radius ≥ 90°), latitudes are clamped to ±90° and the longitude range becomes the full[-180, 180].
-- Anti-meridian-safe bounding-box prefilter
SELECT *
FROM places
WHERE lat BETWEEN :min_lat AND :max_lat
AND (
(:min_lon <= :max_lon AND lon BETWEEN :min_lon AND :max_lon)
OR (:min_lon > :max_lon AND (lon >= :min_lon OR lon <= :max_lon))
);
Warning
A bounding box is not a query for "within radius". It is the rectangle circumscribing the circle, so its corners sit up to 41 % too far from the centre (diagonal vs. radius). Always follow up with an exact distance filter on the candidates:
near = [row for row in db_prefetch(box)
if haversine_km(center, row) <= box["radius_km"]]
Centroid computation¶
center averages the input points as unit vectors on the sphere, not as raw lat/lon:
x = Σ cos(φᵢ)·cos(λᵢ) / n
y = Σ cos(φᵢ)·sin(λᵢ) / n
z = Σ sin(φᵢ) / n
lat = atan2(z, √(x² + y²))
lon = atan2(y, x)
Why this matters:
- Anti-meridian safe. Averaging 179° E and 179° W gives 180° (the correct answer); naive averaging gives 0° (the wrong side of the planet).
- Pole safe. Averaging points around the North Pole yields a sensible high latitude instead of a garbage mean longitude.
- It is the true 3D centroid, not the on-surface centroid. For points spread over a hemisphere or more, the averaged vector shortens, and the result is the direction of that short vector. For clusters covering less than a hemisphere (the normal case) the result is indistinguishable from the geodesic centroid.
- Degenerate case: perfectly antipodal inputs (e.g.
(0,0)and(0,180)) average to the zero vector;atan2(0, 0)returns(0, 0). Guard against that if your inputs can be exactly opposite. - Ordering is irrelevant — the sum is commutative, so input order never changes the output.
import requests
def bounding_box_for(lat: float, lon: float, radius_km: float) -> dict:
"""Typed wrapper with early validation, so we fail before burning a request."""
if not (-90 <= lat <= 90) or not (-180 <= lon <= 180):
raise ValueError("coordinates out of range")
if not (0 < radius_km <= 20000):
raise ValueError("radius must be in (0, 20000] km")
r = requests.post(
"https://geo.toolkitapi.io/v1/geo/bounding-box",
headers={"X-API-Key": "YOUR_KEY"},
json={"center": {"lat": lat, "lon": lon}, "radius": radius_km, "unit": "km"},
timeout=10,
)
r.raise_for_status()
return r.json()
Precision and rounding¶
| Field | Decimal places | Approx. resolution |
|---|---|---|
distance values |
6 | 1 µm in km — far below the model's own error |
center.lat/lon, min_*/max_* |
6 | ~0.11 m at the equator |
The six-decimal rounding is cosmetic: it strips float noise from atan2/asin without losing meaningful accuracy. Don't re-round client-side to fewer places for storage — 6 decimal places is the standard for lat/lon columns and round-trips cleanly.
Error edge cases beyond the table above¶
| Situation | Result |
|---|---|
Two identical points in distance |
200 with 0.0 for that leg — not an error |
| Route containing a zero-length leg | Allowed; that leg contributes 0.0 and appears in legs |
bounding-box radius exactly 20000 |
Allowed (le, not lt) |
center with 2 points |
Allowed (min_length=2); result is the midpoint of the great-circle chord |
lat/lon as strings ("37.77") |
Accepted — Pydantic coerces numeric strings |
distance with 500 points |
Allowed; 499 legs returned. No documented cap on points length, but keep requests under ~1 MB |
unit omitted |
Defaults to km |
method omitted |
Defaults to haversine |