ST_CPAWithin
What is ST_CPAWithin?
ST_CPAWithin is a PostGIS predicate that returns true when two trajectories come within a specified distance of each other at their closest point of approach (CPA).
ST_CPAWithin(geometry trajectory_a, geometry trajectory_b, float maxdist) → booleanInputs must be valid trajectories (see ST_IsValidTrajectory). The function can short-circuit evaluation, making it much faster than comparing ST_DistanceCPA against a threshold in hot paths.
When would you use ST_CPAWithin?
Use ST_CPAWithin for high-volume proximity checks — flagging all pairs of flights whose CPA is under 5 nautical miles, pairs of vessels that came within 500 m of each other, or drones that breached a 50 m safety bubble. It is the right tool for near-miss alerting and regulatory reporting.
1SELECT a.id, b.id
2FROM flights a, flights b
3WHERE a.id < b.id
4 AND ST_CPAWithin(a.track, b.track, 9260); -- 5 NM in metresFAQs
How is ST_CPAWithin faster than computing ST_DistanceCPA and comparing?
ST_CPAWithin can short-circuit as soon as a closer approach than the threshold is found, avoiding the full distance computation. For large joins with tight thresholds this can cut work dramatically.
What units does maxdist use?
The same units as the trajectory's SRS — metres for metric CRSs, degrees for EPSG:4326. Always store trajectories in a projected CRS so that thresholds are meaningful.
What if the trajectories do not overlap in time?
ST_CPAWithin returns false — the CPA is undefined over a non-overlapping M range, so the predicate cannot be satisfied. Use ST_ClosestPointOfApproach (which returns NULL in the non-overlap case) to distinguish "never close enough" from "never overlapping in time".
Does ST_CPAWithin consider Z?
Yes. If both trajectories have Z, the threshold is compared against the full 3D separation. For aviation and submarine work, Z-aware CPA is essential.