Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Distance and nearest service: metric choice before optimization

Last updated: 5 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

The nearest site under straight-line distance may not be the fastest or eligible service point for a real trip.

Choose a metric

For rough regional filtering, great-circle distance between longitude and latitude points is useful. A delivery-time promise needs a road or transit network plus current service constraints. State units, Earth approximation and whether the distance is from site centroid or entrance. Coordinate accuracy can dominate the precision of any distance formula.

Filter eligibility first

A pickup site may be closed, at capacity or outside the customer’s service area. Remove ineligible sites before ranking by distance. If capacity updates arrive late, log the snapshot used for the decision. A nearest result with no available slots is not a useful recommendation. Separate candidate recall from final ranking as in candidate retrieval.

Avoid degree arithmetic

Longitude degrees cover different physical distances at different latitudes. Squared Euclidean distance on raw degree values is not a reliable kilometer estimate. Project to an appropriate local coordinate system for planar work or use a spherical formula for broad distances. Near the antimeridian, naive longitude subtraction can take the long way around.

Check a small case

Customer C-47 is near two pickup sites: one is 0.8 kilometers away across a river, another is 1.4 kilometers away by straight line but connected by road. A straight-line filter can nominate both; travel-time ranking should prefer the reachable site when that is the decision target. The final trace should show metric and network snapshot.

Implementation

python
from math import asin, cos, radians, sin, sqrt

def great_circle_km(lat_a, lon_a, lat_b, lon_b):
    lat_a, lon_a, lat_b, lon_b = map(radians, (lat_a, lon_a, lat_b, lon_b))
    delta_lat = lat_b - lat_a
    delta_lon = lon_b - lon_a
    arc = sin(delta_lat / 2) ** 2 + cos(lat_a) * cos(lat_b) * sin(delta_lon / 2) ** 2
    return 12742 * asin(min(1, sqrt(arc)))

Performance and operating cost

One great-circle calculation is O(1) time and space; scoring N eligible sites is O(N). Spatial indexes reduce candidate search, while road-network shortest paths add graph traversal and time-dependent edge costs.

Common Mistakes

  • Do not measure kilometers by subtracting latitude and longitude degrees.
  • Do not rank closed sites and filter them afterward.
  • Do not present straight-line distance as travel time.

Read next

ai-data
geospatial-analytics
Storage details