Origin-Destination Matrix
Calculate distances between all point pairs
What Is an Origin-Destination Matrix?
An Origin-Destination matrix (OD matrix) is a table that holds the travel cost β distance, time or weight β between every pair of points in two sets of locations. The rows are origins, the columns are destinations, and each cell holds the cost of getting from that row's origin to that column's destination. For n origins and m destinations the matrix has n times m entries. OD matrices are the lingua franca of transportation analysis, accessibility studies, logistics optimisation and any spatial workflow that needs pairwise distances.
The Origin-Destination Matrix tool on gis.tools loads two point layers β origins and destinations β and computes the full pairwise distance matrix in the browser. People search for "origin destination matrix", "od matrix gis", "od cost matrix", "distance matrix calculator", "all pairs distance" and "qgis distance matrix" because OD matrices feed directly into gravity models, accessibility analysis, hub-and-spoke optimisation, retail trade-area analysis and travel surveys.
The basic distinction is between straight-line OD matrices (Euclidean or geodesic distance, ignoring the road network) and network OD matrices (shortest path through a routable graph). The browser tool focuses on straight-line and great-circle distances; for network distances see the Route Along Network and Catchment Analysis tools.
How an OD Matrix Is Computed
The basic algorithm is a double loop over origins and destinations.
Pairwise Distance Loop
For each origin-destination pair, the tool computes a distance using the chosen metric. With n origins and m destinations the cost is O(n * m).
Distance Metrics
- Euclidean (planar): Straight-line distance in projected coordinates. Fast but only correct in a metric CRS over short distances.
- Geodesic (great circle): Distance on the surface of an ellipsoidal Earth model, computed with Vincenty's or Karney's formulas. Correct everywhere but slower.
- Haversine: Distance on a spherical Earth, a simpler approximation to the geodesic. Accurate to ~0.5%.
- Manhattan (taxicab): Sum of horizontal and vertical components, useful in grid-aligned cities.
- Chebyshev: Maximum of horizontal and vertical components, used in chess-king metrics.
Output Formats
The matrix can be exported as:
- A long-format CSV with one row per origin-destination pair (
origin_id, dest_id, distance) - A wide-format CSV with origins as rows and destinations as columns
- A GeoJSON LineString FeatureCollection with one line per pair, attributed with distance
- A summary table with per-origin statistics (mean, min, max, count)
K-Nearest Mode
For very large origin-destination sets, computing the full matrix is wasteful. K-nearest mode keeps only the K closest destinations per origin, reducing output size dramatically.
Distance Threshold
Optionally cap the matrix to pairs with distance below a threshold, dropping irrelevant long pairs.
Key Parameters and Options
Origin Layer
A point GeoJSON, CSV or Shapefile of origin locations. Each origin needs a unique ID attribute.
Destination Layer
A point layer of destinations. Origins and destinations can be the same layer (self-pair OD) or different.
Distance Metric
Geodesic for accurate Earth distances; Euclidean for short distances in a projected CRS; Haversine for fast approximations; Manhattan or Chebyshev for grid-based applications.
Output Format
Long CSV, wide CSV, GeoJSON LineString or summary table.
K-Nearest Filter
Keep only the K nearest destinations per origin. K = 5, 10, 20 are common.
Distance Threshold
Drop pairs above a maximum distance.
Self-Pair Exclusion
When origins and destinations come from the same layer, exclude rows where origin equals destination.
Practical Applications
Retail Trade Area Analysis
A retail chain has 50 store locations and a database of 10000 customer postcodes. An OD matrix gives the distance from every customer to every store. For each customer the closest store is the trade area assignment; aggregating customers by their nearest store yields trade area polygons.
Healthcare Accessibility
A public health analyst computes the distance from every population centroid in a state to every hospital. The minimum distance per population point becomes the accessibility metric used to identify underserved areas.
School Catchment Optimisation
A school district loads pupil home locations and school addresses, computes the OD matrix and balances pupil-school assignments to minimise total travel distance subject to capacity constraints.
Logistics and Last-Mile Delivery
A delivery company has 1 warehouse and 200 daily stops. The OD matrix between the warehouse and each stop, plus pairwise OD between stops, drives a vehicle routing problem (VRP) solver.
Public Transit Network Planning
Transit planners compute OD matrices between residential zones and employment centres to identify high-demand corridors that lack direct service.
Emergency Response Time Modelling
Fire and EMS dispatchers compute OD matrices from each fire station to every address in their jurisdiction to estimate worst-case response times and identify coverage gaps.
Migration and Commuting Studies
Demographers compute OD matrices between residential zones and employment zones to model commuting patterns and validate against census journey-to-work data.
Spatial Interaction Models
Gravity models β commonly used to predict trip volumes between zones β require an OD matrix as input. Doubly-constrained gravity models calibrate trip distributions from observed origin and destination totals.
Step-by-Step Workflow in gis.tools
- Open the Origin-Destination Matrix page on gis.tools.
- Drag your origin point layer (GeoJSON, CSV, Shapefile) into the origin slot.
- Drag your destination point layer into the destination slot. To compute a self-pair OD matrix, drop the same layer into both slots.
- Choose the distance metric: geodesic, Euclidean, Haversine, Manhattan or Chebyshev.
- Optionally enable K-nearest mode and a distance threshold.
- Click Compute. The pairwise loop runs in WebAssembly with vectorised distance kernels.
- Preview the matrix as a table. For the GeoJSON LineString output, lines are drawn on the map with line width or colour proportional to distance.
- Export the matrix as long CSV, wide CSV, GeoJSON or summary table.
- Feed downstream into a routing solver, a gravity model or a Catchment Analysis workflow.
Worked Example: Retail Trade Area for a 30-Store Chain
You have 30 stores and 5000 customer ZIP centroids. You drop the stores layer into origins and the customer layer into destinations. You pick geodesic distance and K-nearest with K = 1 (only the closest store per customer). The tool computes 30 * 5000 = 150000 pairwise distances in about a second, then keeps only the 5000 nearest pairs. The output is a 5000-row long CSV with customer_id, store_id, distance_km. You import the CSV into your BI tool, aggregate customers by store_id, and produce trade area polygons by drawing convex hulls around each store's customer set with Convex / Concave Hull. The exercise reveals that two stores in adjacent suburbs have heavily overlapping trade areas β a candidate consolidation opportunity.
Common Pitfalls and Gotchas
- Euclidean distance in geographic coordinates (degrees) is meaningless β always use geodesic or reproject to a metric CRS first.
- Full OD matrices grow as n * m, which explodes quickly: 1000 origins x 1000 destinations is 1 million pairs.
- K-nearest requires a sort or heap per origin and is more expensive than computing the full matrix in some cases.
- Coordinate precision matters β degraded coordinates from CSV rounding produce inaccurate distances.
- Self-pair distances of zero (when origin == destination) should usually be excluded.
- The matrix records straight-line distance, which can grossly underestimate actual road distance in mountainous or sinuous terrain. Use the Route Along Network for road-based costs.
- Mixing CRSes between origin and destination layers produces wrong distances; reproject one of them first.
- Very large output CSVs (multi-million rows) can exceed browser export size limits β use the K-nearest filter.
Tips for Best Results
- Use geodesic distance for any analysis spanning more than a few kilometres or crossing latitudes.
- Use K-nearest mode whenever you only care about the closest few destinations per origin.
- Reproject both layers to a common metric CRS for Euclidean distances.
- Cap the matrix with a distance threshold for truly long-range analyses to keep the output manageable.
- For network distances, combine with Route Along Network instead of straight-line.
- Export in long format for joining and aggregation in pandas or SQL; use wide format for matrix-style analysis.
- Document the units explicitly (km vs m vs miles) in your output column names.
- Validate against a few hand-computed pairs before trusting the full matrix.
Comparison with Other GIS Approaches
ArcGIS Network Analyst's OD Cost Matrix tool is the canonical network-based implementation. QGIS provides "Distance matrix" in Vector Analysis Tools for straight-line OD. PostGIS's ST_Distance between two tables produces OD matrices in SQL. Python with scipy's cdist or sklearn's BallTree solves Euclidean OD matrices very fast. The OD matrix tool on gis.tools delivers straight-line and geodesic OD computation in the browser without an install. For network-based OD, see the Route Along Network and Catchment Analysis tools.
Performance Considerations
The pairwise loop is O(n * m). 100x100 = 10000 pairs computes instantly. 1000x1000 = 1 million pairs takes a few seconds. 10000x10000 = 100 million pairs strains browser memory and may take minutes. For large problems use K-nearest filtering or chunk the inputs. Vectorised distance kernels in typed arrays make the per-pair cost very small.
Data Privacy and Browser-Based Processing
The origin and destination layers stay in your browser tab. The distance matrix is computed locally and exported as a download blob. No upload, no telemetry, no logging. This matters for sensitive customer addresses, pupil home locations, healthcare patient data and any compliance-bound workflow.
Related GIS Concepts
Network Distance vs Straight-Line: Straight-line distance is fast but unrealistic for travel; network distance respects roads, one-ways and turn restrictions.
K-Nearest: A filtering approach that keeps only the K closest destinations per origin, drastically reducing output size.
Gravity Model: A spatial interaction model that predicts trip volumes between zones based on origin/destination attractiveness and distance.
Cost Matrix: A generalisation of OD matrix where cells can hold cost units other than distance (time, fare, calories, fuel).
Vehicle Routing Problem (VRP): An optimisation problem where an OD matrix is one of the inputs.
Frequently Asked Questions
What is the maximum size OD matrix I can compute?
Practical limit is around 1 million pairs (e.g. 1000x1000) on a typical browser. Larger problems benefit from K-nearest filtering.
Can I compute distances along roads?
Not in this tool β straight-line and geodesic only. For road-network distances use Route Along Network.
What distance metric should I use?
Geodesic for accuracy across long distances; Euclidean in a metric CRS for short distances; Haversine for fast approximations.
Can origins and destinations be the same layer?
Yes β drop the same layer into both slots. Self-pair zero rows are excluded by default.
Can I export a wide-format matrix?
Yes β choose wide CSV format. Long format is more flexible for SQL joins.
Does the tool support time-based OD matrices?
Distance only in this tool. For travel-time matrices use Catchment Analysis with the network-based solver.
Related Tools on gis.tools
Related Tools
View All ToolsStory Map Generator
Create narrative maps with slides and notes
AnalysisGIS Notebook
Save your project state to a single JSON file
AnalysisTime Slider Animator
Animate temporal data with playback controls
AnalysisCoverage Gap Finder
Identify areas not covered by service radii
AnalysisThematic Dashboard
Build interactive dashboards with maps and charts
AnalysisVector Change Detector
Compare two GeoJSON layers to find differences
Analysis100% client-side processing - your data stays private and never leaves your device