How to Measure Distances and Buffers in Metres in Ibis

On this page

Problem statement

Ibis's distance, d_within and buffer take plain numbers and pass them to DuckDB, which measures in whatever units the coordinates are in. On longitude/latitude data that unit is the degree, so d_within(other, distance=500) asks for everything within 500 degrees, and Ibis gives no warning. This page counts the cafés within 500 m of each of Auckland's 121 libraries in Overture Maps places three ways: in raw degrees, with the common "divide by 111,320" conversion, and in metres on New Zealand Transverse Mercator 2000. It then checks the metre figures against buffers and a dissolved catchment.

Quick answer

Convert both sides to a projected CRS in metres with convert, then pass distances in metres:

lib_m = libraries.mutate(lg=_.lg.convert("EPSG:4326", "EPSG:2193"))     # NZTM2000, metres
cafe_m = cafes.mutate(cg=_.cg.convert("EPSG:4326", "EPSG:2193"))
pairs = lib_m.join(cafe_m, lib_m.lg.d_within(cafe_m.cg, distance=500))
print(f"library–café pairs within 500 m: {pairs.count().execute():,}")
library–café pairs within 500 m: 1,213

On NZTM2000 the distance is metres, and 1,213 library–café pairs are within 500 m of each other. The rest of this page shows what the other two ways of writing the same query return, and why neither is close.

Annotated Ibis code that counts pairs within 500 metres on NZTM2000. metres on both sideslib_m = libraries.mutate(lg=_.lg.convert("EPSG:4326", "EPSG:2193"))cafe_m = cafes.mutate(cg=_.cg.convert("EPSG:4326", "EPSG:2193"))pairs = lib_m.join(cafe_m, lib_m.lg.d_within(cafe_m.cg, distance=500))①②③①NZTM2000: coordinates in metres②convert both sides, or the distance is meaningless③ST_DWITHIN(a, b, 500.0): units are the coordinates’1,213 library–café pairs within 500 m spatialworkflow.io
Both sides converted to a metre grid before the distance is used.

From degrees to metres

1. What 500 means on longitude/latitude

in_degrees = libraries.join(cafes, libraries.lg.d_within(cafes.cg, distance=500)).count().execute()
n_lib, n_cafe = libraries.count().execute(), cafes.count().execute()
print(f"d_within(distance=500) on degrees: {in_degrees:,} pairs = every one of {n_lib} × {n_cafe}")
d_within(distance=500) on degrees: 118,580 pairs = every one of 121 × 980

On longitude/latitude, 500 is 500 degrees, more than the whole globe, so every one of the 121 × 980 = 118,580 pairs passes. The query is valid SQL and runs without a warning. The only sign of the mistake is a count equal to the product of the table sizes.

2. Why dividing by 111,320 is not enough

naive = libraries.join(cafes, libraries.lg.d_within(cafes.cg, distance=500 / 111_320)).count().execute()
lat = libraries.lg.y().mean().execute()
print(f"500 m as {500 / 111_320:.5f}°: {naive:,} pairs")
print(f"at {lat:.2f}° one degree is {111_320:,} m north–south but {111_320 * math.cos(math.radians(lat)):,.0f} m east–west")
500 m as 0.00449°: 1,059 pairs
at -36.88° one degree is 111,320 m north–south but 89,046 m east–west

Dividing 500 m by 111,320 m per degree gives 0.00449°, and 1,059 pairs: 154 fewer than in metres. The conversion holds north–south only. At the libraries' mean latitude of 36.88° S a degree of longitude is 89,046 m, so a "500 m" circle in degrees is an ellipse that reaches only about 400 m east and west, and it misses one pair in eight.

Why a radius in degrees is an ellipse at Auckland’s latitude. one degree at 36.88° Snorth–south✓111,320 m per degree✓0.00449° = 500 m✓the conversion holdseast–west✕89,046 m per degree✕0.00449° ≈ 400 m✕the circle is squashedProject to a metre grid instead of converting the radius spatialworkflow.io
A radius in degrees is an ellipse that reaches about 400 m east and west.

3. Count per library, keeping libraries with none

per = (lib_m.left_join(cafe_m, lib_m.lg.d_within(cafe_m.cg, distance=500))
       .group_by(["lib_id", "library"]).aggregate(cafes=_.cafe_id.count()))
counts = per.execute()
print(f"{len(counts)} libraries; median {counts.cafes.median():.0f} cafés within 500 m, {int((counts.cafes == 0).sum())} with none")
print(counts.sort_values(["cafes", "library"], ascending=[False, True]).head(4)[["library", "cafes"]].to_string(index=False))
121 libraries; median 4 cafés within 500 m, 16 with none
                                         library  cafes
                  Media Design School at Strayer     64
Auckland Libraries Corporate Information Service     55
                                          Hāpaia     54
                                    ASB Bank LTC     53

A left_join keeps the 16 libraries with no café within 500 m, which an inner join would drop. Counting cafe_id rather than rows makes them 0 instead of 1. The median library has 4 cafés within 500 m. The top of the list shows that Overture's library category is a classification, not a register: a design school, a council information service and a bank's learning centre rank first, all in the city centre. Filter by confidence or by name before reporting a list like this.

4. Distance to the nearest café, in metres

dist = (lib_m.join(cafe_m, lib_m.lg.d_within(cafe_m.cg, distance=2000))
        .group_by("lib_id").aggregate(nearest_m=(_.lg.distance(_.cg)).min()))
d = dist.execute().nearest_m
print(f"{len(d)} libraries with a café within 2 km; nearest café: median {d.median():,.0f} m, 90th percentile {d.quantile(0.9):,.0f} m")
119 libraries with a café within 2 km; nearest café: median 114 m, 90th percentile 511 m

distance on the projected columns is in metres too. Limiting the join with d_within(…, 2000) first keeps it to pairs worth measuring. 119 of the 121 libraries have a café within 2 km; for them the nearest is a median 114 m away, and nine in ten have one within 511 m.

Buffers and a catchment

The data used on this page

121 libraries and 980 cafés, as Overture Maps' model classifies them (basic_category), from its 2026-11-18.0 places for Auckland. The page reads a saved copy; CDLA Permissive 2.0.

import math
from pathlib import Path

import ibis
import requests
from ibis import _

Path("data").mkdir(exist_ok=True)
name = "overture-auckland-places-2026-11-18.0.parquet"     # from s3://overturemaps-us-west-2/release/2026-11-18.0/theme=places
if not Path(f"data/{name}").exists():
    Path(f"data/{name}").write_bytes(requests.get(f"https://data.spatialworkflow.io/{name}", timeout=300).content)

con = ibis.duckdb.connect()
# the cast is for Ibis 12, which cannot read DuckDB's GEOMETRY('OGC:CRS84') type (see /ibis-keyerror-ogc-crs84/)
places = con.sql(f"select * replace (geometry::GEOMETRY as geometry) from read_parquet('data/{name}')")
libraries = places.filter(_.basic_category == "library").select(lib_id=_.id, library=_.name, lg=_.geometry)
cafes = places.filter(_.basic_category == "cafe").select(cafe_id=_.id, cg=_.geometry)
print(f"{libraries.count().execute()} libraries and {cafes.count().execute()} cafés")
121 libraries and 980 cafés

Example 1: a 500 m buffer is not quite a circle

one = lib_m.order_by("lib_id").limit(1)
area, pts = one.select(a=_.lg.buffer(500).area(), n=_.lg.buffer(500).n_points()).execute().iloc[0]
print(f"buffer(500): {int(pts)} vertices, {area:,.0f} m² against π·500² = {math.pi * 500 ** 2:,.0f} m² ({area / (math.pi * 500 ** 2):.2%})")
buffer(500): 33 vertices, 780,361 m² against π·500² = 785,398 m² (99.36%)

Ibis's buffer takes only a distance, and DuckDB draws the circle as a 33-vertex polygon, 32 segments and the closing point. Its area is 780,361 m², 99.36% of a true circle's. For counting points that is immaterial; for areas summed over many buffers it is a consistent 0.64% short.

Auckland libraries with a café within 2 km and within 500 m. libraries by distance to a cafélibraries121nearestcafé within 2 km119closercafé within 500 m105The nearest café: median 114 m, 90th percentile 511 m spatialworkflow.io
Most libraries have a café close by; the median nearest is 114 m.

Example 2: the area within 500 m of any library

union_km2 = lib_m.aggregate(u=_.lg.buffer(500).unary_union().area()).execute().u.iloc[0] / 1e6
separate_km2 = lib_m.aggregate(s=_.lg.buffer(500).area().sum()).execute().s.iloc[0] / 1e6
print(f"500 m catchments: {separate_km2:.1f} km² added up, {union_km2:.1f} km² dissolved")
500 m catchments: 94.4 km² added up, 70.3 km² dissolved

unary_union in an aggregate dissolves the 121 buffers into one shape, as GeoPandas's dissolve would. Added up, the catchments come to 94.4 km²; dissolved, 70.3 km²: a quarter of the buffered area is counted twice or more where libraries' buffers overlap.

Why Ibis passes the number through

Library–café pairs within 500 m in Auckland counted with a degree conversion and in metres. pairs "within 500 m", 121 libraries × 980 cafés500 / 111,320 degrees1,059 — misses 154NZTM2000, 500 m1,21306501300distance=500 on degrees: all 118,580Raw degrees matched every pair; the usual conversion missed one in eight spatialworkflow.io
Raw degrees matched all 118,580 pairs; the conversion missed 154.

Ibis compiles d_within(other, distance=500) to ST_DWithin(a, b, 500) and buffer(500) to ST_Buffer(geom, 500), and DuckDB's planar functions measure in the coordinates' own units. Neither Ibis nor DuckDB knows those units: on this backend a geometry column carries no CRS (why). The CRS that gives the number its meaning is the one named in your last convert. Projecting both sides to a metre grid is what makes 500 mean 500 m. For a city, a national or local grid is the right one. NZTM2000 is accurate to about one part in 10,000 around Auckland.

Where metres on a grid run out

Checks for distance queries in Ibis. before trusting a distancecount ≠ product of table sizes118,580 = 121 × 980 was the bugboth sides convertedsame CRS, metresbuffers are 33-vertex polygons99.36% of a circledissolve before summing areas94.4 against 70.3 km²A quarter of the summed catchment area was overlap spatialworkflow.io
Four checks that catch a distance in the wrong unit.
  • A count equal to the product of the table sizes. That is the signature of a distance in the wrong unit; 118,580 here. Check it before reading anything else in the result.
  • Converting one side only. If one side is in metres and the other in degrees, the distance between them is meaningless and no error is raised. Convert both sides in the same expression.
  • Large areas. A national grid distorts more towards its edges. For distances across continents, measure on the ellipsoid instead (DuckDB functions Ibis does not wrap).
  • Category noise. Overture's categories are model output: three of the four "libraries" with the most cafés are not public libraries. Distances are only as right as the points they start from.

FAQ

Which projected CRS should I use?

The national or local grid for the area, in metres: NZTM2000 (EPSG:2193) for New Zealand, as here, British National Grid for Great Britain, a UTM zone elsewhere. Avoid Web Mercator (EPSG:3857) for measuring: at Auckland's latitude it stretches distances by about 25%.

Can I keep the data in degrees and still get metres?

For distances, yes: DuckDB's ST_Distance_Spheroid measures on the ellipsoid and returns metres, and Ibis can call it as a built-in function. It expects latitude first, though, and returns NaN for points given longitude first (how to call it). Buffers and d_within have no spheroidal form, so for those, project.