Tabellab

Haversine: Straight-Line Distance from Latitude & Longitude

Lesson 1 of 20Lab

All lessons

You are not signed in — the lab works, but your progress is not saved. Sign up

Lesson 1 of 20 is free. Unlock all 20 hands-on labs, the final exam and your certificate.

Buy course — $9.90
Loading the spreadsheet…

Why every location question starts with a distance

Where should the next shop open? Which customers are close enough for free delivery? How many miles does the van drive every morning, and which store is the natural home of a customer who lives between two of them? All of these questions sound like map problems, and many teams assume they need GIS software to answer them. In practice, the first and most important step is something Excel does perfectly well: turning two pairs of coordinates into a distance in miles or kilometres.

This free lesson is for analysts, operations managers, small-chain owners, sales planners and students who have a list of addresses with latitude and longitude and want real numbers out of it. You do not need any geography background. You only need to be comfortable typing a formula and copying it down a column. By the end you will have a reusable haversine calculator that you can paste into any workbook, and you will understand exactly why the shortcut many people use instead gives wrong answers.

We follow Maple & Rye, a fictional bakery chain with a central kitchen in Mill Creek and five bakery-cafés in the surrounding towns. Every morning a van leaves the kitchen with bread and pastries. The owner wants to know how far each store really is from the kitchen, and how many miles the delivery round adds up to. The lab above uses exactly the same coordinates as this article, so you can check every number as you read. All names, places and numbers are invented for teaching.

The core idea: degrees are not miles

A point on the map is described by two angles. Latitude measures how far north or south of the equator a point is, from −90° at the South Pole to 90° at the North Pole. Longitude measures how far east or west of the Greenwich meridian it is, from −180° to 180°. In data files both are usually stored as decimal degrees, for example 46.302 and −94.246. West and south are negative, so every place in North America has a negative longitude.

The tempting shortcut is to treat the two numbers like x and y on a flat sheet of paper: subtract them, use Pythagoras, multiply by roughly 69 miles per degree, done. The problem is that the Earth is a sphere. One degree of latitude is about 69 miles everywhere, but the lines of longitude meet at the poles, so one degree of longitude gets shorter the further north you go. At the equator it is about 69 miles, at 46° north it is only about 48 miles, and at the poles it is zero. A flat formula that ignores this overstates every east–west distance.

The haversine formula solves this. It gives the great-circle distance, the shortest path between two points over the surface of a sphere, the way a plane or a crow would travel. It needs four inputs (two latitudes, two longitudes) and one constant, the Earth radius. In two lines it looks like this:

a = SIN(Δlat/2)^2 + COS(lat1) × COS(lat2) × SIN(Δlon/2)^2
distance = 2 × R × ASIN(SQRT(a))

Here Δlat and Δlon are the differences between the two points, lat1 and lat2 are the two latitudes, and R is the Earth radius: 3,958.8 miles, or 6,371 km if you want kilometres. The term a is a small number between 0 and 1 that represents how far apart the points are on the sphere. The COS(lat1) × COS(lat2) part is the correction that shrinks longitude differences as you move away from the equator. That is exactly the piece the flat shortcut is missing.

Excel's trigonometric functions (SIN, COS, TAN, ASIN and friends) work in radians, not degrees. A full circle is 360° or 2π radians, so one degree is π/180 ≈ 0.01745 radians. If you feed degrees straight into SIN, Excel does not complain. It simply returns a wrong number. Always convert with RADIANS() or multiply by PI()/180 first.

Worked example: five stores, one kitchen

The kitchen sits at latitude 46.302 and longitude −94.246. The five stores are listed below with their coordinates and every intermediate result of the haversine formula. The Earth radius is kept in its own cell (B3 = 3,958.8) so that you can switch to kilometres by typing 6,371 and nothing else changes.

StoreLatitudeLongitudeΔlat (rad)Δlon (rad)Haversine aDistance (mi)
Alder Falls46.215-94.118-0.0015180.0022341.1729×10⁻⁶8.57
Birch Lake46.448-94.3050.002548-0.0010301.7495×10⁻⁶10.47
Cedar Bend46.118-94.432-0.003211-0.0032463.8400×10⁻⁶15.52
Dunmore46.356-93.8740.0009420.0064935.2470×10⁻⁶18.14
Elk Prairie46.063-93.991-0.0041710.0044516.7238×10⁻⁶20.53
Daily round trip146.46

Look at the rows for a moment. Dunmore has the smallest latitude difference of the faraway stores (only 0.054°) but the largest longitude difference (0.372°). Elk Prairie is further south and slightly less far east. The haversine distances, 18.14 miles to Dunmore and 20.53 miles to Elk Prairie, already include the fact that at 46° north an east–west degree is worth only about 48 miles. The nearest store, Alder Falls, is 8.57 miles away, and the full out-and-back round trip, two times the sum of the five distances, is 146.46 miles. That is a straight-line lower bound: real roads are always longer, which is exactly what lesson 5 of this course deals with.

The formulas behind the table, with the kitchen in B2:C2, the radius in B3 and the first store in row 6, are:

  • D6 =RADIANS(B6-$B$2): latitude difference in radians.
  • E6 =RADIANS(C6-$C$2): longitude difference in radians.
  • F6 =SIN(D6/2)^2+COS(RADIANS($B$2))*COS(RADIANS(B6))*SIN(E6/2)^2: the haversine term a.
  • G6 =2*$B$3*ASIN(SQRT(F6)): the distance in miles.
  • G12 =2*SUM(G6:G10): the daily round trip, out to each store and back.

Notice the dollar signs. The kitchen and the radius are fixed points that every row refers to, so they get absolute references ($B$2, $C$2, $B$3). The store coordinates change row by row, so they stay relative (B6, C6). That one decision is what lets you write the formula once in row 6 and copy it down to row 10, or to row 10,000.

46.146.246.346.4-94.4-94.2-94.0Longitude (°)Latitude (°)Alder FallsBirch LakeCedar BendDunmoreElk PrairieKitchenHaversine distance from the kitchenAlder Falls8.57Birch Lake10.47Cedar Bend15.52Dunmore18.14Elk Prairie20.53Round trip to all five stores:146.46 miles per day
The five Maple & Rye stores around the Mill Creek kitchen, drawn roughly to scale, with the haversine distance of each store. The dashed lines are straight-line paths, not roads.

Step by step: build the haversine calculator in Excel

Here is the full procedure, written so that you can repeat it on your own data. It works in every version of Excel from 2010 onwards, in Excel for the web and in Google Sheets.

  1. Put the origin in fixed cells: a name in A2, the latitude in B2 and the longitude in C2. Type the Earth radius in B3 (3958.8 for miles, 6371 for kilometres) and label it in A3 so nobody wonders what the number means.
  2. List the destinations in a block below, one per row, with latitude in column B and longitude in column C. If your data comes as "46.215, -94.118" in one cell, split it first with Data › Text to Columns (delimiter: comma) or with =TEXTSPLIT(A6,",") in Excel 365.
  3. Check the signs. Everything west of Greenwich must have a negative longitude and everything south of the equator a negative latitude. A store that suddenly appears 6,000 miles away almost always has a missing minus sign.
  4. In D6 type =RADIANS(B6-$B$2). Type B2, then press F4 (Mac: Cmd+T) to turn it into $B$2. In E6 type =RADIANS(C6-$C$2).
  5. In F6 type the haversine term: =SIN(D6/2)^2+COS(RADIANS($B$2))*COS(RADIANS(B6))*SIN(E6/2)^2. Watch the brackets: the ^2 belongs outside SIN(…), so you square the sine, not the angle.
  6. In G6 type =2*$B$3*ASIN(SQRT(F6)) and format the cell with Home › Number › Decrease Decimal to two decimals (or press Ctrl+1 and choose Number, 2 decimals).
  7. Select D6:G10 and press Ctrl+D (Mac: Cmd+D) to fill all four formulas down. Alternatively double-click the small fill handle in the bottom-right corner of the selection.
  8. In G12 add the round trip: =2*SUM(G6:G10). Press Ctrl+` to show all formulas at once and check that every row points to its own store and to the same $B$2, $C$2 and $B$3.
  9. Sanity-check one row against a map. Pick any store, measure the straight-line distance with the ruler tool of an online map service, and compare. The two should agree to within a fraction of a mile for distances like these.
In Excel 365 you can pack the whole calculation into one readable formula with LET: =LET(lat1,RADIANS($B$2),lat2,RADIANS(B6),dlat,lat2-lat1,dlon,RADIANS(C6-$C$2),a,SIN(dlat/2)^2+COS(lat1)*COS(lat2)*SIN(dlon/2)^2,2*$B$3*ASIN(SQRT(a))). It returns the same value as the four helper columns. Helper columns are still the better choice while you are learning, because you can see every step.

Why the shortcut fails: a direct comparison

To see how much the curvature matters, compare the haversine result with the shortcut many spreadsheets use: =SQRT((B6-$B$2)^2+(C6-$C$2)^2)*69. That formula treats a degree of longitude as if it were 69 miles long, which is only true at the equator.

Haversine vs. naive “degrees × 69” (miles)Haversine (correct)Naive Pythagoras on degrees051015202530Miles from the Mill Creek kitchenAlder Falls8.610.7Birch Lake10.510.9Cedar Bend15.518.1Dunmore18.125.9Elk Prairie20.524.1
The naive formula overstates every distance, and the error grows with the east–west part of the trip. Dunmore lies almost due east of the kitchen, so it is overstated by roughly 8 miles.

For Birch Lake, which lies almost due north, the two methods nearly agree (10.5 versus 10.9 miles), because latitude degrees really are about 69 miles long. For Dunmore, almost due east, the shortcut says 25.9 miles while the true distance is 18.1. Summed over the round trip the shortcut adds about 33 miles a day. If you used those numbers to set delivery fees, size catchments or compare sites, every eastern location would look worse than it really is.

There is a middle way for short distances: the equirectangular approximation multiplies the longitude difference by the cosine of the mean latitude before applying Pythagoras, =$B$3*SQRT(D6^2+(E6*COS(RADIANS((B6+$B$2)/2)))^2). Within a few dozen miles it agrees with haversine to about a hundredth of a mile here. Haversine costs no more effort in a spreadsheet, though, and it stays correct over long distances, so it is the sensible default.

Location analytics in Excel: distances, catchments and territories
Location analytics in Excel: from coordinates to distances, catchments, territories and site decisions.

Common mistakes and how to spot them

  • Forgetting to convert to radians. SIN(46.3) is calculated as if 46.3 were radians, which is more than seven full turns. The result is a plausible-looking but meaningless number. Spot it: distances that jump around wildly or are bigger than half the Earth's circumference (about 12,450 miles).
  • Squaring the angle instead of the sine. SIN(D6/2^2) or SIN((D6/2)^2) are not the same as SIN(D6/2)^2. Spot it: compare one row with a hand calculation or an online calculator.
  • Mixing up latitude and longitude. Many data sources list "lon, lat" (GeoJSON does), others "lat, lon". Spot it: latitudes must be between −90 and 90. A "latitude" of −94 is impossible, so it must be a longitude.
  • Missing minus signs. A longitude of 94.246 instead of −94.246 puts the store in China. Spot it: a single distance that is thousands of miles larger than the rest.
  • Relative references on the origin. Without $ signs the second row compares store 2 with the cell below the kitchen, which is empty or holds the radius. Spot it: the first row is right and every other row is wrong. Press Ctrl+` and read the formulas.
  • Mixing units. Radius in kilometres, delivery cost per mile. Spot it: label the radius cell with the unit and keep one unit through the whole model.
  • Treating straight-line distance as driving distance. Rivers, lakes and road networks make real trips longer. Use haversine as the base and apply a circuity factor or a routing service when you need drive times.

Quick reference: functions and shortcuts used

Function or shortcutWhat it does hereExample
RADIANS(angle)Converts degrees to radians, which SIN, COS and ASIN expect=RADIANS(B6-$B$2)
SIN(x), COS(x)Trigonometric sine and cosine of an angle in radians=SIN(D6/2)^2
ASIN(x)Inverse sine, returns an angle in radians=ASIN(SQRT(F6))
SQRT(x)Square root=SQRT(F6)
PI()π, the alternative to RADIANS: degrees × PI()/180=(B6-$B$2)*PI()/180
SUM / SUMPRODUCTAdds the distances, or computes them in one array formula=2*SUM(G6:G10)
LET (Excel 365)Names intermediate values inside one formula=LET(a, …, 2*R*ASIN(SQRT(a)))
F4Cycles a reference through $B$2, B$2, $B2, B2 (Mac: Cmd+T)Select B2 in the formula bar, press F4
Ctrl+DFills the formula of the top cell down the selection (Mac: Cmd+D)Select D6:D10, press Ctrl+D
Ctrl+`Toggles between showing values and showing formulasAudit all five rows at once

Real-world uses

  • Delivery zones and fees. A restaurant or retailer charges by distance band: free within 3 miles, a small fee up to 8 miles, no delivery beyond. Haversine distance plus a lookup table sets the fee for every address automatically.
  • Field service and sales routes. A technician's or sales rep's daily list of visits can be ranked by distance from the depot, and the straight-line total gives a quick lower bound for mileage claims and planning.
  • Nearest branch or warehouse. For every customer, find the closest location so that orders, complaints or service tickets go to the right team. This is lesson 3 of this course.
  • Catchment and market sizing. Count customers, households or revenue within 5, 10 and 15 miles of a store to see how much of its trade comes from close by and how far its pull really reaches.
  • Site selection. Before signing a lease, check how far a candidate site is from existing stores (to avoid cannibalisation) and from the target customers, and combine the distances with rent, footfall and other criteria in a scoring model.

What you will build in the rest of this course

This first lesson gives you the one formula every other lesson depends on. The remaining 19 lessons are part of the paid course ($9.90 one-time) and turn it into a complete location-analytics toolkit, each with its own interactive lab and the same Maple & Rye data.

Distance Matrix: Every Customer Town × Every Store. You write a single haversine formula with mixed references (B$2, $A5 and friends) and fill an 8 × 5 matrix of every customer town against every store in one move. Then you summarise each store's reach. Mixed references are the skill that makes the difference between an afternoon of copying formulas and one drag.

Nearest Store per Customer with MIN and INDEX/MATCH. From the matrix you pick the nearest store for every customer town, return its name with INDEX/MATCH, count the households each store serves and chart the result. This is the basis of service areas, ticket routing and "your nearest branch" features.

Catchment Rings: Counts and Revenue within a Radius. You size the Alder Falls store's primary, secondary and tertiary catchment with COUNTIFS and SUMIFS on distance bands and estimate its annual sales, the way retail analysts present a trade area.

Drive-Time Proxy: Circuity Factor and Speed Assumptions. Straight lines are not roads. You turn miles from the kitchen into estimated drive minutes with a circuity factor and road-speed assumptions and count the stops reachable within 25 minutes, without paying for a routing API.

Territory Balancing: Workload per Sales Rep. You calculate the yearly workload of three wholesale reps from visits and travel, measure how unbalanced the territories are and test what happens when one border account moves to another rep.

Huff Gravity Model: Probabilities and Market Share. Customers do not always go to the nearest store. You build a Huff model for six towns and four bakery-cafés, two of them competitors, to estimate each store's expected sales and Maple & Rye's market share from size and distance.

New Site Selection: Weighted Scoring and a Scatter Map. You score five candidate sites for the sixth café on four criteria, combine them with weights and plot candidates and existing stores on a longitude/latitude scatter chart that works as a simple map, ready to show in a meeting.

Summary

Latitude and longitude are angles, not distances, and a degree of longitude shrinks as you move away from the equator. The haversine formula handles that correctly with four Excel functions: RADIANS to convert, SIN and COS for the term a, and ASIN with SQRT to turn it into a distance with the Earth radius. Keep the origin and the radius in absolute references, copy the formula down, and you have straight-line distances for any list of places. For Maple & Rye the result is a daily round trip of 146.46 miles, and a clear picture of which stores sit far out east.

Now scroll up to the lab and build it yourself: convert the differences to radians in columns D and E, calculate the haversine term in F, the distance in G and the round trip in G12. The Coach checks each step and tells you exactly where a formula goes wrong.

Frequently asked questions

How do I calculate the distance between two coordinates in Excel?

Use the haversine formula: =2*3958.8*ASIN(SQRT(SIN(RADIANS(lat2-lat1)/2)^2+COS(RADIANS(lat1))*COS(RADIANS(lat2))*SIN(RADIANS(lon2-lon1)/2)^2)). It returns the great-circle distance in miles. Replace 3958.8 with 6371 for kilometres.

Why do I need RADIANS in the haversine formula?

Excel's SIN, COS and ASIN functions expect angles in radians, while coordinates are stored in degrees. RADIANS converts degrees to radians, and without it Excel returns a number that looks plausible but is wrong.

What Earth radius should I use?

The commonly used mean Earth radius is 3,958.8 miles or 6,371 kilometres. Because the Earth is not a perfect sphere, haversine distances can differ from survey-grade results by up to about half a percent, which is fine for business analysis.

Is haversine distance the same as driving distance?

No. Haversine gives the straight-line distance over the Earth's surface. Driving distances are longer because roads bend around terrain and water, so analysts often multiply by a circuity factor or use a routing service.

Can I use Pythagoras on latitude and longitude instead?

Only if you first scale the longitude difference by the cosine of the latitude. Plain Pythagoras on degrees overstates east–west distances, by up to about 40% at 46° north in this lesson's example.

Does the haversine formula work in Google Sheets?

Yes. Google Sheets has the same RADIANS, SIN, COS, ASIN and SQRT functions, so the formula works unchanged. Only the shortcut for absolute references differs slightly on some keyboards.

Keep going: Location Analytics in Excel: Distances, Catchments & Territories

This free lab is lesson 1 of 20. Unlock the other 19 hands-on labs, the final exam and your certificate for a one-time $9.90.

  1. Distance Matrix: Every Customer Town × Every Store
  2. Nearest Store per Customer with MIN and INDEX/MATCH
  3. Catchment Rings: Counts and Revenue within a Radius
  4. Drive-Time Proxy: Circuity Factor and Speed Assumptions
  5. Territory Balancing: Workload per Sales Rep
  6. Huff Gravity Model: Probabilities and Market Share
  7. New Site Selection: Weighted Scoring and a Scatter Map
  8. Quick Distance Checks: Bounding Boxes and the Equirectangular Shortcut
  9. Cleaning Coordinates: Swapped, Missing-Sign and Out-of-Area Points
  10. Customer Penetration by Town and Distance Band
  11. Fitting a Distance-Decay Curve with LN, SLOPE and EXP
  12. Calibrating the Huff Model: Choosing β from Survey Shares
  13. Delivery Zones: Distance-Tiered Fees and Zone Profitability
  14. Grid Heat Maps: Binning Orders into Map Cells with INT and COUNTIFS
  15. Whitespace Analysis: Unserved Potential by Town
  16. Cannibalisation: Sales Transfer When a New Store Opens
  17. Sales vs Catchment: Regression, Residuals and a Site Forecast
  18. New Site Business Case: Payback in Low, Base and High Scenarios
  19. Final Project: Store Network Location Dashboard

Buy course — $9.90 See the full course