Find nearest features and handle ties#
Find the nearest features to each location and decide how to handle equally distant matches. Start with two eager Geometry frames in the same live session and with equal active CRSs. Use a projected CRS with known units, or unspecified planar coordinates whose units are known. For geographic inputs or different CRSs, first put the layers in the same coordinate system.
Retain locations or report matches only#
Choose how='left' to retain each location, including one without a match. Choose how='inner' to report matches only. If you set a max_distance, it must be finite and positive and uses the coordinate units.
Create locations.csv.
qid,x,y
A,0,0
B,10,0
Create features.csv.
fid,x,y
west,-1,0
east,1,0
In a Python environment that can import cugeo.geometry, read both files into one session. For each location, find the nearest feature or features, keeping matches at most one metre away.
import cugeo.geometry as cg
s = cg.Session()
opts = {'geometry': {'type': 'point_xy', 'x': 'x', 'y': 'y'}, 'srid': 3857}
locations = cg.read_file('locations.csv', options=opts, session=s)
features = cg.read_file('features.csv', options=opts, session=s)
hits = locations.sjoin_nearest(
features, how='left', max_distance=1, distance_col='distance'
)
print([(r['qid'], r['fid'], r['distance']) for r in hits.to_arrow().to_pylist()])
Check that A has both west and east at distance 1, in either order, and that B has a row with missing feature and distance. The cutoff includes its endpoint, and the eager join keeps every exact native tie. NULL and EMPTY geometries cannot supply a match.
If you need one assignment per location occurrence, apply a secondary rule after the join. For example, choosing the smallest stable feature ID assigns A to east.
Rank matches in saved SQL#
For relations with id and compatible geom columns, use this nearest-query shape.
SELECT a.id, n.id
FROM a
CROSS JOIN LATERAL (
SELECT b.id
FROM b
ORDER BY a.geom <-> b.geom
LIMIT 2
) n
Ascending distance ranks NULL distances last. The fixed positive literal limit can cut through a tie, and direct ST_KNN skips absent distances. For the admitted correlation and predicate placement, see nearest-query support in Spatial SQL and query-shape support.