Functional Weave
Code in Python

geo.bounding-box

Latitude/longitude bounding box that contains every point within a distance of a centre point.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 15 tests, run in TypeScript, Python and Rust.

What it does

The smallest latitude/longitude box that contains every point within a given distance of a centre. It is the cheap first filter for "find everything within 10 km": query the box with an index, then check the real distance (`geo.distance`) on what comes back.

## Method

For example

  • bounding_box(51.507, -0.128, 10,000) → min lat 51.417, min lng -0.272, max lat 51.597, max lng 0.017 10 km around central London
  • bounding_box(0, 0, 100,000) → min lat -0.899, min lng -0.899, max lat 0.899, max lng 0.899 100 km around the origin is square in degrees on the equator
  • bounding_box(60, 10, 100,000) → min lat 59.101, min lng 8.201, max lat 60.899, max lng 11.799 at 60 degrees north the longitude span is about twice the latitude span

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def bounding_box(lat: float, lng: float, distance_metres: float) -> BoundingBox
latfloatcentre latitude in degrees, -90 to 90
lngfloatcentre longitude in degrees, -180 to 180
distance_metresfloatsearch radius in metres, 0 or more
returnsBoundingBoxminLng > maxLng means the box crosses the antimeridian

The type it declares, generated into your project

@dataclass(frozen=True)
class BoundingBox:
    """Degrees, rounded outward to 7 decimals so the box always contains the circle."""

    min_lat: float
    min_lng: float
    max_lat: float
    max_lng: float

Your code names it in one line, in the file that uses it

from fune.geo.bounding_box import bounding_box  # geo.bounding-box@^1
impl/python.py · 164 lines · open · raw
import math
from typing import Tuple

from .geo_bounding_box_types import BoundingBox

# The latitude/longitude box that contains every point within a distance of a
# centre, by the method of J. P. Matuschek, "Finding Points Within a Distance
# of a Latitude/Longitude Using Bounding Coordinates"
# (http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates).
#
# The trigonometry is written out below instead of calling math.sin and
# friends, because the platform maths library may differ in the last bit
# between Python, JavaScript and Rust. Only correctly-rounded IEEE 754
# operations (+ - * / sqrt floor) are used, in the same order in all three.

# IUGG mean radius R1 of the GRS 80 ellipsoid (Moritz, Journal of Geodesy 74 (2000)).
EARTH_RADIUS_METRES = 6371008.8
# Ten millionths of a degree, about a centimetre.
SCALE = 10000000.0
# Within a millionth of a grid step of a 7-decimal value counts as that value,
# so a centre of 51.5074 stays 51.5074 rather than becoming 51.5073999.
SNAP = 0.000001

PI = 3.141592653589793
HALF_PI = PI / 2
DEGREES = PI / 180

S3, S5, S7, S9, S11 = -1 / 6, 1 / 120, -1 / 5040, 1 / 362880, -1 / 39916800
S13, S15, S17 = 1 / 6227020800, -1 / 1307674368000, 1 / 355687428096000
C2, C4, C6, C8, C10 = -1 / 2, 1 / 24, -1 / 720, 1 / 40320, -1 / 3628800
C12, C14, C16, C18 = 1 / 479001600, -1 / 87178291200, 1 / 20922789888000, -1 / 6402373705728000
A3, A5, A7, A9, A11 = -1 / 3, 1 / 5, -1 / 7, 1 / 9, -1 / 11
A13, A15, A17, A19, A21 = 1 / 13, -1 / 15, 1 / 17, -1 / 19, 1 / 21


def _sin_small(r: float) -> float:
    s = r * r
    p = S17
    p = S15 + s * p
    p = S13 + s * p
    p = S11 + s * p
    p = S9 + s * p
    p = S7 + s * p
    p = S5 + s * p
    p = S3 + s * p
    return r + r * s * p


def _cos_small(r: float) -> float:
    s = r * r
    p = C18
    p = C16 + s * p
    p = C14 + s * p
    p = C12 + s * p
    p = C10 + s * p
    p = C8 + s * p
    p = C6 + s * p
    p = C4 + s * p
    p = C2 + s * p
    return 1 + s * p


def _sin_cos(x: float) -> Tuple[float, float]:
    k = math.floor(x / HALF_PI + 0.5)
    r = x - float(k) * HALF_PI
    sr = _sin_small(r)
    cr = _cos_small(r)
    quadrant = k % 4
    if quadrant == 0:
        return sr, cr
    if quadrant == 1:
        return cr, -sr
    if quadrant == 2:
        return -sr, -cr
    return -cr, sr


def _atan_unit(u: float) -> float:
    v = u
    v = v / (1 + math.sqrt(1 + v * v))
    v = v / (1 + math.sqrt(1 + v * v))
    v = v / (1 + math.sqrt(1 + v * v))
    s = v * v
    p = A21
    p = A19 + s * p
    p = A17 + s * p
    p = A15 + s * p
    p = A13 + s * p
    p = A11 + s * p
    p = A9 + s * p
    p = A7 + s * p
    p = A5 + s * p
    p = A3 + s * p
    return 8 * (v + v * s * p)


def _asin_positive(x: float) -> float:
    # (1 - x)(1 + x) keeps precision near 1.
    if x >= 1:
        return HALF_PI
    t = x / math.sqrt((1 - x) * (1 + x))
    return HALF_PI - _atan_unit(1 / t) if t > 1 else _atan_unit(t)


# Outward rounding: a lower bound goes down and an upper bound goes up, so
# rounding can only grow the box, never cut the circle.
def _round_down(x: float) -> float:
    return float(math.floor(x * SCALE + SNAP)) / SCALE + 0.0


def _round_up(x: float) -> float:
    return float(math.ceil(x * SCALE - SNAP)) / SCALE + 0.0


def _check_number(value: object, what: str) -> None:
    if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
        raise TypeError("%s must be a finite number" % what)


def bounding_box(lat: float, lng: float, distance_metres: float) -> BoundingBox:
    """The box containing every point within distance_metres of (lat, lng)."""
    _check_number(lat, "latitude")
    _check_number(lng, "longitude")
    _check_number(distance_metres, "distance")
    if lat < -90 or lat > 90:
        raise ValueError("latitude must be between -90 and 90 degrees")
    if lng < -180 or lng > 180:
        raise ValueError("longitude must be between -180 and 180 degrees")
    if distance_metres < 0:
        raise ValueError("distance must be 0 or more metres")
    lat, lng, distance_metres = float(lat), float(lng), float(distance_metres)

    r = distance_metres / EARTH_RADIUS_METRES
    r_degrees = r / DEGREES
    min_lat = lat - r_degrees
    max_lat = lat + r_degrees

    if min_lat > -90 and max_lat < 90:
        sin_r = _sin_cos(r)[0]
        cos_lat = _sin_cos(lat * DEGREES)[1]
        d_lng = _asin_positive(sin_r / cos_lat) / DEGREES
        min_lng = lng - d_lng
        max_lng = lng + d_lng
        # Past the antimeridian the bound comes round the other side, leaving
        # min_lng > max_lng: the box is the two strips either side of 180.
        if min_lng < -180:
            min_lng += 360
        if max_lng > 180:
            max_lng -= 360
    else:
        # The circle reaches a pole, so it covers every longitude.
        if min_lat < -90:
            min_lat = -90.0
        if max_lat > 90:
            max_lat = 90.0
        min_lng = -180.0
        max_lng = 180.0

    return BoundingBox(
        min_lat=_round_down(min_lat),
        min_lng=_round_down(min_lng),
        max_lat=_round_up(max_lat),
        max_lng=_round_up(max_lng),
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add geo.bounding-box
Download for Python geo.bounding-box-1.0.0-python.fune · 12,693 bytes sha256 d08bddc5df8f46b262747ae1dba928ece4b298fe425fda23000514f63cdd6641

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./geo.bounding-box-1.0.0-python.fune, or fetch it from a terminal with fune pull geo.bounding-box@1.0.0:python.

The whole function, every language, is one file too: geo.bounding-box-1.0.0.fune, 25,515 bytes, sha256 74658290375ebdd1c98f319e6acc3f3438a4e0b2156f09909818f7c1c02ba2c9. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before geo.bounding-box

after — your function gets the result and the arguments, and returns the final result.

# fune: after geo.bounding-box

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show geo.bounding-box --steps.

# fune: step geo.bounding-box after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
10 km around central London 51.507, -0.128, 10,000 → min lat 51.417, min lng -0.272, max lat 51.597, max lng 0.017
100 km around the origin is square in degrees on the equator 0, 0, 100,000 → min lat -0.899, min lng -0.899, max lat 0.899, max lng 0.899
at 60 degrees north the longitude span is about twice the latitude span 60, 10, 100,000 → min lat 59.101, min lng 8.201, max lat 60.899, max lng 11.799
southern and eastern hemispheres -33.869, 151.209, 5,000 → min lat -33.914, min lng 151.155, max lat -33.824, max lng 151.263
zero distance is the point itself, not nudged a grid step outward by its binary value 51.507, -0.128, 0 → min lat 51.507, min lng -0.128, max lat 51.507, max lng -0.128
crossing the antimeridian wraps maxLng round, so minLng > maxLng 0, 179.9, 50,000 → min lat -0.45, min lng 179.45, max lat 0.45, max lng -179.65
a centre on the antimeridian wraps minLng round 45, -180, 1,000 → min lat 44.991, min lng 179.987, max lat 45.009, max lng -179.987
a circle over the north pole covers every longitude (the asin formula alone gives NaN here) 89.9, 0, 20,000 → min lat 89.72, min lng -180, max lat 90, max lng 180
a circle over the south pole covers every longitude -89.95, 45, 10,000 → min lat -90, min lng -180, max lat -89.86, max lng 180
just short of the pole the longitude span is very wide but not global 80, 0, 1,100,000 → min lat 70.107, min lng -81.634, max lat 89.893, max lng 81.634
Show the other 5 tests
CaseArgumentsExpected
a radius larger than the Earth is the whole globe 0, 0, 30,000,000 → min lat -90, min lng -180, max lat 90, max lng 180
negative distance is an error 51.5, 0, -1 → error: distance must be 0 or more metres
latitude out of range is an error 95, 0, 1,000 → error: latitude must be between -90 and 90 degrees
longitude out of range is an error 0, -181, 1,000 → error: longitude must be between -180 and 180 degrees
a distance that is not a number is an error 0, 0, 10km → error: distance must be a finite number

More from the author

J. P. Matuschek, "Finding Points Within a Distance of a Latitude/Longitude Using Bounding Coordinates", http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates. The Earth is a sphere of radius 6,371,008.8 m (IUGG mean radius, as in `geo.distance`). The angular radius is r = d / R; latitudes are centre ± r; the longitude half-width is asin(sin r / cos lat), which is wider than r away from the equator (about twice as wide at 60°).

## Edge cases

- **Poles.** If the circle reaches or crosses a pole, it covers every longitude: the box is clamped to ±90 and runs from -180 to 180. Without this check the asin formula is asked for asin of more than 1 and returns NaN. - **The antimeridian.** A bound that passes ±180 comes round the other side, so minLng > maxLng. That is the signal that the box is two strips, minLng..180 and -180..maxLng; a query must OR them rather than use BETWEEN. - **Zero distance** is the point itself. **Negative distance** is an error. - A radius larger than the Earth gives the whole globe.

## Rounding outward

Bounds are rounded to 7 decimal places (about 1 cm), outward: the minimums down and the maximums up, so rounding can only grow the box and never cut off part of the circle. A value within a millionth of a step of a 7-decimal value (about 1e-13 degrees) is taken to be that value, so a centre of 51.5074 with distance 0 stays 51.5074 rather than becoming 51.5073999 because its binary value sits a hair below.

## Why the answers are identical in every language

As in `geo.distance`, the trigonometry is written out using only correctly rounded IEEE 754 operations (+ − × ÷, sqrt, floor) in the same order in all three languages, instead of calling the platform's Math.sin, which may differ in the last bit and could tip a value across a rounding step. On 4,000 random inputs the unrounded and rounded bounds were bit-for-bit identical in TypeScript, Python and Rust.

Files

PathBytes
README.md2,222
impl/python.py5,186
impl/rust.rs6,756
impl/typescript.ts5,605
vectors.json2,743