Distance Matrix Calculator
N×N pairwise distance matrix between any 2–50 points worldwide. Haversine crow-flies in the browser, optional driving distance via Valhalla for ≤15 points, heatmap visualization, sortable list view, and CSV export in either long or wide format. Free, no sign-up, no API key.
What is a distance matrix and why use this tool
A distance matrix is an N×N grid where cell (i, j) is the distance from point i to point j. For N points there are N² cells, of which N(N−1)/2 are unique because the matrix is symmetric (distance from A to B equals distance from B to A) and the diagonal is zero. Distance matrices are the standard input for many spatial and operations-research methods — clustering, multidimensional scaling, sales territory assignment, vehicle routing problems, proximity analysis, and access studies.
The web is short on free distance-matrix tools. Google deprecated the free tier of its Distance Matrix API in 2018 and now charges $5 per 1,000 elements ($5 for a single 32×32 matrix, $5,000 for a 1,000×1,000 matrix). Mapbox, NextBillion, distancematrix.ai, and Maptive all charge in the same range — between $0.50 and $2 per 1,000 elements. For one-off planning work, a hobby project, or a research analysis, the cost is enough to deter use.
This tool fills that gap. The crow-flies portion runs entirely in your browser using the haversine formula — no API key, no rate limit, and no per-element charge. The driving portion piggybacks on the open-source Valhalla service hosted by FOSSGIS, with a 15-point cap to stay polite. You add 2–50 points, the matrix renders instantly, and the long-or-wide CSV export is one click. For the volumes most users actually need (5–50 points), the tool is a complete replacement for the paid APIs.
How to compute a pairwise distance matrix
Six steps from blank canvas to a fully-exported matrix.
- Add your first batch of points. Type a city, address, or landmark in the search box and pick a result, tap "Use My Location" to seed with your GPS, or click anywhere on the world map. Each point becomes a numbered, colour-coded pin on the map and a row in the points list. Up to 50 points are supported.
- Bulk-import from a list — addresses or coordinates. Click "Paste list" to open a textarea. One point per line: either a literal "lat, lng" pair like "40.7128, -74.006" or an address like "Eiffel Tower" or "1600 Pennsylvania Ave, Washington DC". Coordinates are direct; addresses are geocoded one-by-one through Photon at a 600 ms politeness rate. Failed lines are skipped silently.
- Pick the unit and view. Switch the unit to miles, kilometres, or nautical miles in the dropdown — the matrix re-renders instantly. Toggle between matrix view (full N×N grid with heatmap colouring and sticky headers) and list view (sortable one-row-per-pair table with bearing). On phones the tool defaults to list view, but you can flip back to matrix anytime.
- Optionally enable driving distance. Tick "Driving distance" to fetch real road distance and drive time for every unique pair. The toggle is disabled above 15 points (105 pairs) to keep load on the open-source Valhalla service polite. Driving cells appear underneath crow-flies in matrix view and as separate columns in list view as they finish loading.
- Click cells to draw on the map. In matrix view, click any cell to draw the great-circle line between those two points on the map and scroll it into focus. In list view, click "Show on map" on any row. The line is dashed red and is antimeridian-aware, so a Tokyo → Honolulu pair renders correctly across the date line instead of wrapping around the globe.
- Export to CSV — long, wide, or TSV clipboard. Three export options at the bottom. "Long CSV" produces one row per unique pair with origin, destination, all three units, and driving columns — ideal for joins and database imports. "Wide CSV" produces the full N×N matrix grid in your chosen unit, ready to drop into a spreadsheet. "Copy TSV" puts the same wide matrix on the clipboard for instant paste into Excel or Google Sheets. The full state is also encoded in the URL hash, so copying the URL shares the exact matrix.
What people use the distance matrix for
Seven common patterns we see in the search analytics and customer support inbox.
Logistics — warehouse to customer route planning
A regional logistics operator with a few warehouses and many customers needs the pairwise distance from every warehouse to every customer to assign shipments correctly. Drop the warehouse coordinates as the first set of points, paste the customer list, and read the warehouse-to-customer block of the matrix. The wide CSV export is one paste away from a spreadsheet that drives the assignment optimization. For 10 warehouses and 30 customers, the matrix is 40×40 — well inside our 50-point cap.
Real estate — amenity proximity for every home
A buyer's agent with five candidate homes and ten amenities (the nearest schools, hospitals, parks, transit hubs) wants a single grid showing distance from every home to every amenity. Paste all 15 addresses, geocode them in one batch, then read the matrix. The colour-coded heatmap makes it obvious which homes are isolated and which are well-served by nearby amenities. For an MLS report, the wide CSV exports cleanly into a presentation table.
Sales territory assignment
A sales operations team has 15 customers and 5 reps based out of different home offices. The pairwise customer-to-rep matrix is the input to a territory-assignment optimization that minimizes total drive time. Toggle "Driving distance" to get the road version of the matrix (105 pairs is well inside the 15-point cap), export the long CSV, and the assignment is a one-line solve in any spreadsheet or Python notebook. The bearing column doubles as a rough territory-boundary cue.
Tourism — hotel to attraction matrix
A travel blogger reviewing a city wants the distance from every recommended hotel to every recommended attraction. Add the 8 hotels and 20 attractions, and the matrix is a 28×28 grid where the relevant block is hotels-on-rows × attractions-on-columns. Sort the list view by crow-flies ascending to find the most central hotels. Embed the wide CSV in the article as a sortable HTML table and let readers filter to find the hotel closest to the attractions they care about most.
Scientific research — clustering and MDS
Pairwise distance matrices are the standard input for hierarchical clustering, multidimensional scaling (MDS), k-medoids, DBSCAN, and many spatial-statistics methods used in ecology (species range overlap), archaeology (site adjacency), epidemiology (case clustering), and social science. Paste up to 50 study sites, export the long CSV, and load it directly into R's "dist" object, Python's scipy.spatial.distance.squareform, or a phyloseq distance matrix. The haversine math is exactly what these libraries expect; no further conversion needed.
Healthcare access analysis
A regional health planner studying access to specialty care needs the distance from every population centre (ZIP code centroid or census tract) to every specialty clinic. The pairwise matrix shows which communities are underserved (high minimum distance to the nearest clinic) and which clinics have overlapping catchment areas. With the driving toggle, the analysis switches from straight-line "potential access" to road-based "realised access" — the more honest figure for patients without private vehicles.
Field service routing
HVAC techs, fibre installers, locksmiths, and home-care nurses dispatched on day routes use pairwise distances as the input to a TSP optimizer that picks the best visit order. The matrix is the data; the TSP is the algorithm. Export the long CSV from this tool and feed it into Google OR-Tools or a dedicated dispatcher. With 12 stops, the matrix is 12×12 (66 unique pairs) and computes both crow-flies and driving in seconds.
Worked example — 5 California cities
A 5×5 crow-flies distance matrix for the largest cities in California. Distances in statute miles, computed with haversine on a spherical Earth (R = 6,371 km). The diagonal is zero (a city is zero miles from itself); the upper and lower triangles mirror each other (the matrix is symmetric).
| Los Angeles | San Francisco | San Diego | Sacramento | Fresno | |
|---|---|---|---|---|---|
| Los Angeles | — | 347 mi | 111 mi | 360 mi | 209 mi |
| San Francisco | 347 mi | — | 446 mi | 75 mi | 158 mi |
| San Diego | 111 mi | 446 mi | — | 471 mi | 314 mi |
| Sacramento | 360 mi | 75 mi | 471 mi | — | 156 mi |
| Fresno | 209 mi | 158 mi | 314 mi | 156 mi | — |
The pair “San Francisco–San Diego” is the longest at 446 miles (effectively the full length of California). The pair “San Francisco–Sacramento” is the shortest at 75 miles. Fresno comes out as the most central — its row has the lowest mean distance to the other four cities — which is consistent with its geographic position in the Central Valley. This is the exact 5-city example loaded by the “5 California cities” quick example button on the tool above; click it to load the same five points and see the full matrix on the map.
The mathematics behind the matrix
Three formulas drive every cell in the matrix. They are below in case you want to verify, audit, or reimplement them.
| Quantity | Formula | Notes |
|---|---|---|
| Cell (i, j) — haversine | d(i,j) = 2R · asin(√(sin²(Δφ/2) + cos φᵢ · cos φⱼ · sin²(Δλ/2))) | φ = latitude (rad), λ = longitude (rad), R = 6,371 km. Δφ = φⱼ − φᵢ, Δλ = λⱼ − λᵢ. |
| Symmetry | d(i,j) = d(j,i); d(i,i) = 0 | Crow-flies on a sphere is a metric. We compute the upper triangle and mirror. |
| Initial bearing | θ(i,j) = atan2(sin Δλ · cos φⱼ, cos φᵢ · sin φⱼ − sin φᵢ · cos φⱼ · cos Δλ) | Forward azimuth at the origin, used in list view. Asymmetric: θ(i,j) ≠ θ(j,i). |
| Computational complexity | O(N²/2) cells; O(N²) memory | For N = 50: 1,225 unique pairs, ~0.1 ms total in browser. For N = 500: ~125,000 pairs, ~10 ms. |
How the tool actually works
1. Matrix math — synchronous, in the browser
Every time the points list changes, we recompute the full N×N crow-flies matrix synchronously in the browser using a tight double-loop and the haversine formula. For N = 50 that is 1,225 unique haversine evaluations, which JavaScript on a modern phone finishes in well under a millisecond. We compute only the upper triangle and mirror the values to the lower triangle (the matrix is symmetric); the diagonal is hard-coded to zero. There is no server round-trip — adding or removing a point updates the matrix instantly.
2. Driving distance — Valhalla, throttled parallel calls
When the driving toggle is on (and N ≤ 15), we enumerate all N(N−1)/2 unique pairs and fire them at the open-source Valhalla service via our /api/route endpoint, throttled to 4 concurrent requests to stay polite to the upstream. Per-pair results are cached for 24 hours upstream so common matrices get fast subsequent loads. Results stream back into the matrix as they complete — you do not have to wait for all 105 pairs to see the first 4. The 15-point cap exists to keep upstream load reasonable; above 15 the toggle is disabled with a tooltip.
3. Heatmap rendering — log-scale HSL gradient
Each cell in the matrix view is colour-coded with a log-scale HSL gradient: light green (lowest distance) → soft red (highest distance). The log scale matters because pairwise distances often span orders of magnitude — for a continental matrix like the 10 largest US cities, distances range from ~50 mi (Dallas–Fort Worth) to ~2,500 mi (NYC–LA). Linear interpolation would compress everything into the green end and mask the inner structure. The log scale gives every order of magnitude equal visual weight, so adjacent clusters and outliers both pop.
4. CSV export formats — long, wide, and TSV
The two CSV formats answer different questions. Long format writes one row per unique pair: origin_label, origin_lat, origin_lng, destination_label, destination_lat, destination_lng, distance_mi, distance_km, distance_nm, driving_mi, driving_min. This is the right input for joins, pivots, database imports, and clustering libraries (R\u2019s dist object and Python\u2019s scipy.spatial.distance.squareform both reconstruct the matrix from a long list). Wide format writes the full N×N grid in your selected unit; first row is header labels, first column is row labels, body is the matrix. Open it in Excel and you have an instant matrix table. TSV to clipboard is the same wide grid as tab-separated values, which Excel and Google Sheets paste into without an import dialog.
How this tool compares to paid distance-matrix APIs
Quick comparison against the major paid distance-matrix APIs on the web. Most have no free tier; pricing is per 1,000 matrix elements (a 32×32 matrix = 1,024 elements). For most use cases (5–50 points), our tool replaces them entirely.
| Feature | SimpleMapLab | Google Distance Matrix API | Mapbox Matrix API | NextBillion | distancematrix.ai | Maptive |
|---|---|---|---|---|---|---|
| Free | ✓ unlimited | ✗ paid only | ✗ paid only | ✗ paid only | Limited free tier | ✗ paid only |
| Up to 50 points / 2,500 elements | ✓ | ✓ (paid) | ✓ (paid) | ✓ (paid) | Limited (≤25) | ✓ (paid) |
| Crow-flies (haversine) | ✓ | ✗ | ✗ | ✗ | Limited | ✗ |
| Driving distance | ✓ (≤15 pts) | ✓ (paid) | ✓ (paid) | ✓ (paid) | Paid | ✓ (paid) |
| CSV export — long format | ✓ | API only | API only | API only | ✗ | API only |
| CSV export — wide / matrix format | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Heatmap visualization | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Sticky-header N×N table | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Click-cell to draw on map | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Antimeridian-aware drawing | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| No sign-up, no API key | ✓ | ✗ key required | ✗ key required | ✗ key required | ✓ | ✗ key required |
| Pricing | $0 | $5 / 1k elements | $0.50–$2 / 1k | $1 / 1k | Limited free | $0.50–$1 / 1k |
CSV format guidance — long vs wide
Both CSV formats encode the same information; the right choice depends on what you are going to do with the data.
Long format — one row per pair
Long format is the right choice if the next step is a database import, a join with another table, a pivot, a chart, or a clustering library. Each row contains the origin, the destination, all three units, and the driving columns. Skipping self-self pairs and deduplicating to j > i means N(N−1)/2 rows for N points — for a 10-point matrix, 45 rows. Sample header:
origin_label,origin_lat,origin_lng,destination_label,destination_lat,destination_lng,distance_mi,distance_km,distance_nm,driving_mi,driving_min
Wide format — N×N matrix grid
Wide format is the right choice if the next step is a presentation table, a heatmap chart, a Markdown matrix in an article, or visual inspection. The first row is destination headers; the first column is origin headers; the body is the matrix in your selected unit. For a 10-point matrix, that is 11 rows × 11 columns = 121 cells. Same data, different shape.
Related tools and resources
For a cumulative trip distance instead of a pairwise matrix — e.g., a multi-stop tour rather than every-pair lookup — our multi-stop route distance sums the distance along an ordered list of waypoints with optional best-order TSP optimization. For a single A→B comparison with side-by-side driving and detour percentage, crow flies distance is the focused tool. For a clean two-point haversine number with multiple unit toggles, distance between two places does just that one thing.
For finding all the places within a given radius of a single point — a different proximity question — see find cities in radius and find ZIP codes in radius. For converting an address list to clean coordinates first (so you can paste literal lat/lng into the matrix tool above), use address to coordinates.
For visual annotation rather than distance math: CSV to map plots a CSV of lat / lng on an interactive map with category coloring, pin drop map lets you drop up to 100 pins with notes, and bearing calculator gives the four-flavour bearing math (initial, final, rhumb-line, magnetic) for any one pair in your matrix.
Frequently asked questions
Data sources & methodology
Crow-flies matrix:haversine formula on a spherical Earth, R = 6,371 km (IUGG mean radius), computed pairwise in the browser. Public-domain math.
Driving distance and time: per-pair lookup against Valhalla routing engine (open-source, Linux Foundation) on OpenStreetMap data, hosted by FOSSGIS at valhalla1.openstreetmap.de. Capped at 15 points (105 pairs) for polite usage. 1,500 km path-length cap per pair on the free instance.
Place-name search: Photon (typo-tolerant geocoder by Komoot) for autocomplete, Nominatim (OpenStreetMap reverse geocoder) for map-click reverse geocoding.
Maps: MapLibre GL JS with OpenFreeMap “Liberty” vector tiles. Last reviewed 5 May 2026.
More distance and routing tools
Cumulative trip mileage across an ordered tour with TSP best-order optimization.
Single-segment great-circle distance with multiple unit toggles.
Isochrone — how far you can drive, bike, or walk in N minutes.
Plot a CSV of lat / lng on an interactive map with category coloring.