Finding customers within two kilometers of a warehouse appears to require one distance function. Swapped coordinates, projected values mislabeled as angles or degrees compared directly with 2000 can nevertheless produce a plausible list. This article addresses data and conversational-analytics engineers working with two-dimensional surface point distances. Route planning and survey-grade three-dimensional calculations are outside its scope.
Define the distance question before accepting coordinates
Specify what the endpoints represent. A warehouse coordinate might identify the building center, loading entrance or site gate; a customer location might come from field positioning or address matching. Those choices affect records near a two-kilometer boundary. A distance function cannot repair a coordinate assigned to the wrong business object. Our proposed data contract records object ID, location meaning, source, acquisition time and accuracy information.
Decide whether the service radius means surface straight-line distance or road travel distance. Points on opposite riverbanks can be close while a vehicle faces a substantial detour. Straight-line distance can shortlist candidates, but cannot promise delivery time. Road-distance requirements need a routing calculation with explicit map versions and restrictions; renaming a straight-line result is not sufficient.
For model or local facility coordinates, unit and coordinate-transform acceptance for 3D models explains units, origins and axes. Local metric coordinates do not automatically have a geographic reference, however. Without reliable control points or an established transformation, keep them separate instead of assigning WGS 84 and including them in nationwide queries. This article adds geographic-reference and distance-operation boundaries rather than repeating static-model matrix transformations.
GeoJSON specifies order; valid ranges do not establish provenance
RFC 7946 uses WGS 84 geographic coordinates. The first two position-array values are longitude and latitude, in that order, expressed in decimal degrees.[1] State lon and lat or the array order explicitly in an interface contract. Do not infer the meaning of an unexplained x,y list. Other interfaces require their own order checks.
Check types, finite values, missingness and the business coverage area before ingestion. Out-of-contract longitude or latitude outside ±90 degrees should be quarantined. A harder error passes range checks: the constructed point (12,45), swapped to (45,12), remains numerically valid while identifying a different location. Range checks reject some errors; they do not prove correct axis order.
Use several geographically separated control points confirmed by the source owner to check place names, coordinate order and map positions. Avoid relying entirely on points near the origin or symmetric positions. Preserve raw fields, store cleaned lon and lat separately and version the conversion rule. If an entire batch shifts, inspect its source declaration before manually dragging points to match a basemap.
Missing locations must not become (0,0), which is a valid numerical coordinate. Stale positions, addresses matched only to city centers and low-resolution administrative locations need separate states. Mark accuracy as unknown when no evidence exists. Adding decimal places changes presentation, not positioning reliability.
Assigning an SRID and transforming coordinates are different operations
PostGIS ST_SetSRID sets reference-system metadata without changing coordinate values.[2] When input is confirmed as WGS 84 longitude and latitude, ST_SetSRID(ST_MakePoint(lon, lat), 4326) constructs a declared point. Confirmation of the source is essential: the function does not determine whether the data actually belong to that system.
For known projected input, retain the correct source SRID before using ST_Transform to reach the target reference system. The latter changes coordinates and depends on available transformation support.[3] Do not relabel meter-valued projected coordinates as 4326, or repeatedly try different SRIDs for unknown data until a map looks plausible.
Our proposed processing record preserves four stages: raw values and provenance, confirmed source reference system, transformed target values, and transformation software and rule versions. Keep errors and raw values when transformation fails. Never silently return original coordinates bearing a target-system label. High-precision or special-area work also needs appropriately qualified review of the operation and required resources.
A round-trip transformation detects some implementation faults, but cannot independently validate the reference system. Incorrect source metadata followed by a consistently incorrect outward and return transformation may still reproduce the original numbers. Use independent controls and destination-position checks, not reversibility alone.
The data type determines the distance unit
PostGIS ST_Distance computes two-dimensional planar distance for geometry in the reference system's units. For geography it defaults to spheroidal geodesic distance in meters.[4] Consequently, a distance between two SRID 4326 geometry points must not be interpreted as meters. An interface using ST_Distance(a,b) < 2000 without declaring types and units is too ambiguous to accept.
Confirmed WGS 84 surface points can use geography for meter-based radius queries. Controlled regional engineering analysis can instead use a suitable projected geometry. The decision requires coverage, tolerated error, supported operations and index testing—not a blanket claim about speed or accuracy. A projection having meter units does not mean it preserves ground distance everywhere.
Consider a constructed warehouse A=(0,0), customer B=(0.01,0) and customer C=(1,0), all assumed to be confirmed WGS 84 longitude and latitude. Their planar angular geometry distances from A are 0.01 and 1. Comparing these with 2000 includes both, but does not implement a two-kilometer filter. Near the equator those longitude differences correspond to approximately 1.11 km and 111 km, so the filter should include B and exclude C. These approximations explain scale; they are not measured results.
An expression to validate in the target environment is ST_DWithin(a::geography, b::geography, 2000). Here a and b are correctly constructed SRID 4326 points, not arbitrary raw columns, and 2000 is in meters. The geography overload uses meter thresholds and includes a bounding-box mechanism that can use available indexes.[5] Inspect the actual execution plan; a function name alone does not guarantee index use.
Implement the path from raw input to queryable locations
First create a staging layer preserving external object ID, raw coordinate text, source reference system, axis order, location timestamp and batch ID. Count parsing errors separately from missing metadata. Avoid guessing units, swapping axes, transforming positions and overwriting raw input in one opaque ingestion function: that makes the first source of a shift difficult to recover.
Second validate by source. After range checks, compare controls and the business coverage area, then generate standardized geographic points using confirmed rules. Unknown reference systems remain pending investigation and are excluded from default distance statistics. Accepted plus quarantined records must reconcile with input totals. Results should disclose how many objects were excluded because locations were unknown.
Third standardize the server-side representation. For point-radius queries spanning regions, a materialized geography column with a corresponding GiST index is one option, avoiding unplanned per-query conversions. If geometry is retained and transformed or cast in queries, evaluate indexes for the actual expression. Validate plans and latency at representative data volumes; do not promise speedup factors without measurements.
Fourth constrain parameters. Require nonnegative radius, a fixed unit and an explicitly sourced center point, with a business limit on permitted range. Return object ID, distance and unit, location version and calculation definition. For pagination, sort by distance and a stable ID together and maintain a consistent data version so moving locations do not shift an object between pages.
Fifth retain a release comparison: original batch, standardized records, control results, query inputs and reference outputs. When a conversion rule changes, generate a candidate version, compare object counts, geographic coverage and boundary membership, then switch default queries. On failure, restore the previous version rather than replacing the only recoverable coordinates.
Accept boundaries and counterexamples, not just visible map points
Cover at least six cases: zero distance for the same point; the expected B and C membership above; swapped axes that remain in valid ranges; missing coordinates that do not become zero; incorrect or absent source SRIDs quarantined; and points just inside and outside the threshold. Record expected states and tolerated errors rather than checking only successful SQL execution.
Boundary control points should come from an independent reference or validated calculation chain. Test distances slightly below, equal to and slightly above the agreed radius, after defining whether the boundary is included. Separate numerical error from location error. If positioning uncertainty is tens of meters, displaying six decimal places does not make a two-kilometer boundary trustworthy to centimeters.
For near-boundary records with inadequate accuracy, we recommend business states such as definitely inside, definitely outside and review required. Derive the tolerance band from positioning evidence and business consequences, not one universal number of meters. This is an application-level proposal, not a confidence interval supplied automatically by PostGIS. Do not invent probabilities when there is no error model.
Finally add an antimeridian case and high-latitude cases relevant to the coverage area to expose improper reliance on longitude subtraction. This procedure does not prove road accessibility, proximity between floors or an asset's physical presence. No PostGIS performance experiment was conducted. Official function documentation was checked on November 8, 2026; freeze PostGIS, PROJ and data versions for deployment acceptance.
