simplemaplab

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.

Or click the map to add. Up to 50 points.
Try:
Loading map…

Add 2 or more points to start

  • 1Search by city, address, or landmark
  • 2Click anywhere on the map
  • 3Paste a list of coordinates or addresses (CSV)
Try one of these to see it instantly

Up to 50 points for crow-flies. Up to 15 if you toggle driving distance.

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 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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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 AngelesSan FranciscoSan DiegoSacramentoFresno
Los Angeles347 mi111 mi360 mi209 mi
San Francisco347 mi446 mi75 mi158 mi
San Diego111 mi446 mi471 mi314 mi
Sacramento360 mi75 mi471 mi156 mi
Fresno209 mi158 mi314 mi156 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.

QuantityFormulaNotes
Cell (i, j) — haversined(i,j) = 2R · asin(√(sin²(Δφ/2) + cos φᵢ · cos φⱼ · sin²(Δλ/2)))φ = latitude (rad), λ = longitude (rad), R = 6,371 km. Δφ = φⱼ − φᵢ, Δλ = λⱼ − λᵢ.
Symmetryd(i,j) = d(j,i); d(i,i) = 0Crow-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 complexityO(N²/2) cells; O(N²) memoryFor 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.

FeatureSimpleMapLabGoogle Distance Matrix APIMapbox Matrix APINextBilliondistancematrix.aiMaptive
Free✓ unlimited✗ paid only✗ paid only✗ paid onlyLimited 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 formatAPI onlyAPI onlyAPI onlyAPI 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 / 1kLimited 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

A distance matrix is an N×N table where cell (i, j) is the distance from point i to point j. "Pairwise" simply means every pair gets its own number — 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 (a point is zero distance from itself). Distance matrices are the standard input for clustering, multidimensional scaling, sales territory assignment, logistics optimization, and many spatial-statistics methods.
Yes. Click "Paste list", drop one address (or one literal "lat, lng" pair) per line, and the tool geocodes addresses through Photon at a 600 ms politeness rate. For a 50-point list of addresses that is roughly 30 seconds of geocoding. Coordinates are direct (no geocoding needed). Lines that fail geocoding are skipped silently — the rest are appended.
Up to 50 for crow-flies (haversine) — that gives 50 × 49 / 2 = 1,225 unique pairs, computed in milliseconds in the browser. Driving distance is capped at 15 points (105 unique pairs) to stay polite to the open-source Valhalla routing service. Above 15, the driving toggle is disabled with a tooltip; crow-flies still works for the full 50.
Yes. The crow-flies matrix is recomputed on every points change, synchronously, in the browser. There is no server round-trip and no rate limit — adding or removing a point updates all N² cells instantly. Driving cells stream in as the parallel Valhalla calls complete (max 4 concurrent), so a 12-point matrix with driving on takes a few seconds to fully fill in.
Driving distance comes from the FOSSGIS-hosted Valhalla service, which is free to use on a fair-share basis. 15 points means 105 unique pairs — well within polite usage. 50 points would mean 1,225 pairs, which would saturate the upstream service. The cap is enforced client-side: the toggle is disabled above 15. Crow-flies has no such cap because it runs entirely in the browser.
Very. Haversine on a spherical Earth (R = 6,371 km, the IUGG mean radius) is accurate to within ~0.5% for any practical purpose. The 5-decimal lat / lng rounding is sub-metre. For sub-metre work you would switch to the WGS-84 ellipsoid with Vincenty’s formulas, but for trip planning, real estate, logistics, and clustering analysis the spherical model is more than sufficient.
Cleanly. The haversine formula has no antimeridian issue — it is unaffected by which longitude you pick. The drawing math splits the great-circle path at any longitude jump greater than 180° and renders one or more LineString features, so a Tokyo → Honolulu pair shows the correct northward arc across the date line rather than wrapping around the globe.
Yes, three ways. (1) "Wide CSV" downloads the full N×N grid in your chosen unit — open it in Excel and you have an instant matrix table. (2) "Long CSV" downloads one row per unique pair with origin, destination, all three units, and driving — ideal for joins, pivots, and database imports. (3) "Copy TSV" puts the same wide matrix on the clipboard as tab-separated values; paste straight into a spreadsheet without any import dialog.
An asymmetric matrix has different distances for A→B versus B→A. For crow-flies on Earth, the matrix is always symmetric — there is no direction to the great-circle distance. For driving, the matrix can be slightly asymmetric (one-way streets, asymmetric tolls, peak vs off-peak detours), but in practice the difference is small and we treat the matrix as symmetric to halve the number of upstream calls. If you need true asymmetric driving distance, use the multi-stop route distance tool with paired waypoints.
Because crow-flies distance is a metric — by definition, distance from A to B equals distance from B to A. The diagonal is zero because a point is zero distance from itself. We compute only the upper triangle (the N(N−1)/2 unique pairs) and mirror the values to the lower triangle. This halves the compute cost and is exactly what classical distance-matrix consumers (clustering libraries, MDS implementations) expect as input.
Yes — that is one of the canonical use cases. Export the long CSV, reshape it to a square matrix in your environment of choice (R's "as.dist", Python's scipy.spatial.distance.squareform, MATLAB's "squareform"), and feed it into hierarchical clustering, k-medoids, DBSCAN, or MDS. The haversine math we use is what these libraries expect for geographic data — no projection or further conversion is needed.
The driving distance and time we return are free-flow estimates based on posted speed limits and road category — they do not account for real-time traffic, weather, or construction. Compared to off-peak Google Maps, we are typically within 5–10%; during rush hour on a congested freeway, we will under-estimate by a wider margin. For traffic-aware routing you need a paid API (Google Distance Matrix, Mapbox Matrix). For most planning use cases — territory assignment, real estate proximity, clustering input — free-flow is the right number.
Yes, optimized. Touch targets are ≥44 px, inputs use 16 px font (which prevents iOS zoom-on-focus), the result section auto-switches to list view at 720 px (matrix view is still available — just toggle), the map collapses to 320 px, and the table hides the bearing column on narrow phones and the driving columns on very narrow phones (<380 px). You can build a 50-point matrix on an iPhone and email the wide CSV.
Yes. The full state of the tool — every point with its lat / lng / label, plus the unit, view mode, and driving flag — is encoded as compact JSON, base64-ed, and stored in the URL hash. Copy the URL from the address bar and send it; anyone with that link will load the same matrix. No sign-up, no server-side database, no expiration. For 50 points with long labels the URL gets long but still well under the 32 KB browser limit.
Multi-stop computes the cumulative distance along an ordered tour — N waypoints means N−1 segments, and the answer is one number (or two with round-trip on). The distance matrix computes every pair, regardless of order — N points means N(N−1)/2 unique pairs, and the answer is a full grid. Use multi-stop when you want a trip total; use the matrix when you want the underlying pairwise distances that drive clustering, assignment, and proximity analysis.

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

Multi-Stop Route Distance

Cumulative trip mileage across an ordered tour with TSP best-order optimization.

Distance Between Two Places

Single-segment great-circle distance with multiple unit toggles.

Drive Time Map

Isochrone — how far you can drive, bike, or walk in N minutes.

CSV to Map

Plot a CSV of lat / lng on an interactive map with category coloring.