Python exercise · about 5 minutes · free
Distance Between Two Places: The Haversine Formula
Which stores are within 50 km of a customer? The Earth is round, so straight-line maths on latitude and longitude is wrong.
The haversine formula gives the great-circle distance between two points given in degrees: a = sin^2(dlat/2) + cos(lat1) x cos(lat2) x sin^2(dlon/2), d = 2R x asin(sqrt(a)) with R = 6371 km. Convert degrees to radians first. For radius searches over millions of points, first filter with a cheap bounding box or a spatial index (geohash, H3, PostGIS), then apply the exact distance.
Prices, versions and service names last checked 2026-11-19. They change, so confirm on the official pages before you rely on them.
Your quest: Write
haversine_km(lat1, lon1, lat2, lon2) and within_radius(stores, lat, lon, km): stores maps a name to (lat, lon); return the names within km (inclusive), nearest first (ties: name).Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
Hint
Convert with <code>math.radians</code>. Sort by <code>(distance, name)</code>.Output appears here.