### Share

At distances of 30km or less, **your Earth may be flat**. Consider implementing features such as local search, geo-fencing or nearby place scanning in mobile phone applications. Using **distance calculations that ignore the curvature of the Earth can save you computation time **and complexity in your code.

A depiction of consequences a flat Earth would have for navigators in the 1500s and 1600s

**Our planet Earth is not actually flat**; high school geography may have taught you the Earth is in fact a form of sphere, closer to **an imperfect ellipsoid which is referred to by Earth scientists and geographers as a “geoid.”** You may not have know that last term but, someone, a family member or friend, probably pulled out a globe one day and showed you a 3d representation of the Earth. At some point you realized the Earth is in fact a curved surface.

Putting the globe aside for a moment, **it can be beneficial in various cases to ignore the complexity of our 3d world**; cases like the local-search illustrated in the Google Maps screenshot below.

A typical local search returns distances within 5 to 10 miles (less than 20 km where straightline distance will provide only a small error relative to rounded distance units in kilometers or miles)

**Euclidean distance**

**Euclidean distance** calculates straight line distance between two points on a flat surface and hence does not take into consideration the curvature of the Earth.

`Euclidean or "straight line distance":`

`straight_line_distance = sqrt ( ( x2 - x1 )**2 + ( y2 - y1 )**2 )`

**Error involved in a “flat-Earth” distance calculation**:

less than 30 meters (100 ft) for latitudes less than 70 degrees

less than 20 meters ( 66 ft) for latitudes less than 50 degrees

less than 9 meters ( 30 ft) for latitudes less than 30 degrees

(These error statements reflect both the convergence of the meridians and the curvature of the parallels.)

–(Chamberlain, 1996)

In other words **the closer you are to the Equator, the less error there is involved by using straight-line distance**. Distance in most apps is expressed in kilometers (km) or miles (mi) and many cities are at latitudes less than 50 degrees North or South of the Equator. So the typical error you are looking at is less than .2 km (20 meters), at a lower latitude, like near Los Angeles, California, the error is around .1 km which is not bad since most users are looking for the point of interest to appear, or looking for parking, at .5 to .25 km away. Next I will show how corrections can be made to reduce this error moving North or South of the Equator.

### Modification to account for error in distance calculation:

Taking into account the length of a degree of longitude at higher latitudes as `deglen`

consider the following **distance function in Python and its explanation**.

“…the length of a (1) degree of longitude depends on the latitude: a (1) degree of longitude spans 111 km on the Equator, but half of that on 60° North. Adjusting for this is easy: multiply the longitude by the cosine of the latitude. Then… take the Euclidean distance between the two points, and multiply by the length of a degree (in km)”

–(Salonen, “Geographic distance can be simple and fast”)

**Modified straight_line_distance function**:

```
distance(lat1, lng1, lat2, lng2):
deglen = 110.25
x = lat1 - lat2
y = (lng1 - lng2)*cos(lat2)
return deglen*sqrt(x*x + y*y)
```

If we consider the average city user, most users can be said to be looking for points of interest that are 10 miles or closer to their current location (roughly 16 km).

The error in calculation of distance using Euclidean distance with modification for varying widths between degrees longitude at North or South 65 degrees latitude is less than .04% in distance calculation only surpassing 1% error in distance at 89 degrees latitude. Eighty-nine degrees latitude in the Northern hemisphere is the North Pole

–(Salonen, “Geographic distance can be simple and fast”)

Euclidean distance does not take into consideration the curvature of the Earth, however it returns results rather quickly with an error that could be said to be negligible at atypical user’s range and use case. Using straight line or Euclidean distance can be said to be **using your location in a 2d manner; **which is fine if you are just trying to find say a bank within walking distance or a short drive or a nearby cafe to write your latest blog post for mydigitalsauce.com.

## Manhattan distance

Another important consideration in calculating distance for the average city location app user is **city blocks**. Straight line distance may not help a user as much as a simple approximation of the **distance to complete a large city block**, the two perpendicular sides of the triangle in the Pythagorean theorem, between source and destination. **Consider this scenario for instance:**

Manhattan distance vs. straight line distance; Euclidean distance or “as the crow flies”

“An urban area, where the objective is to calculate the distance between customers’ homes and various retail outlets. In this situation, distance takes on a more specific meaning, usually road distance, making straight line distance less suitable. Since streets in many cities are based on a grid system, the typical trip may be approximated by what is known as the **Manhattan, city block or taxi cab distance**.”

–(Fotheringham, 2002)

`Manhattan or "block" distance:`

```
block_distance = ( abs( x2 - x1 ) + abs( y2 - y1 ) )
```

## Spherical distance: Great circles & Haversine distance

The above is a very simple equation that many of us are probably already familiar with. Now lets have a look at the **Haversine Formula; an accurate way to calculate distance using the latitude and longitude of the two points on a sphere**. Since we are working with a sphere this time we encounter a curved line as opposed to a straight line. This curved line, much like the one between “P” and “Q” in the graphic below, is based on a relative slice of a “great circle”; a circle whose radius is that of the sphere, in our case an approximate radius of the Earth. Points “u” and “v” are “antipodal” points, which means they are the same distance from one another on an infinite number of intersecting great circles, as can be inferred by the diagram below.

The **Haversine formula** is referred to by mathematicians and professional geographers as…

a re-formulation of the spherical law of cosines that

works well with small distances.

–(Kettle, “Distance on a sphere: The Haversine Formula”)

The Haversine distance formula is expressed with the following variables and expressions, where **φ** is latitude, **λ** is longitude, **R** is earth’s radius (average radius = 6,371km):

```
# Haversine distance "d" is calculated on third line
a = sin²(φB - φA/2) + cos φA * cos φB * sin²(λB - λA/2)
c = 2 * atan2( √a, √(1−a) )
d = R ⋅ c
```

The illustration above can be used to interpret the Haversine distance equation. Angles at points “A”, “B” & “C” correspond to distances “a”, “b” & “c”. For the Haversine distance we use “a” to calculate “c” which is equivalent to the distance between point “A” and “B,” source and destination respectively. “O” can be interpreted as the center of the Earth in this spherical interpretation, so “OC”, “OB” & “OA” all are equivalent to the radius of Earth.

The code snippet below is written in **Python** and contains a **function to calculate Haversine distance between two points**. You can use the following coordinates for testing if you like:

Coordinates in decimal degrees for Starbucks at “source”: 33.5429645, -117.7857923, in Laguna Beach, California; “destination”: 33.6521467, -117.7480071, Starbucks in Irvine, California; Or use some coordinates for two places near you.

`Haversine distance function (Python):`

```
def haversine(source: object, destination: object):
import math
lon1, lat1 = source
lon2, lat2 = destination
R = 6371000 # radius of Earth in meters
phi_1 = math.radians(lat1)
phi_2 = math.radians(lat2)
delta_phi = math.radians(lat2 - lat1)
delta_lambda = math.radians(lon2 - lon1)
a = math.sin(delta_phi / 2.0) ** 2 + math.cos(phi_1) * math.cos(phi_2) *
math.sin(delta_lambda / 2.0) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
meters = R * c # output distance in meters
kilometers = meters / 1000.0 # output distance in kilometers
meters = round(meters, 3)
kilometers = round(kilometers, 3)
print(f"Distance: {meters} m")
print(f"Distance: {kilometers} km")
```

–(Kettle, “Distance on a sphere: The Haversine Formula”)

Run this function with your “source” and “destination” coordinate objects (tuples of lat and long) with command line Python or an IDE that will run your Python code like so:

`haversine([33.5429645, -117.7857923], [33.6521467, -117.7480071])`

Then run the same coordinates with the “straight_line_distance” formula, or modified version, shown earlier in this post. If the source and destination are less than 30 kilometers apart you should not see a major difference.

## Conclusions

**In summary**, if you want to save time and complexity in development of your next app that uses a local-search or consistently is calculating distance to points of interest (POI) that are less than 30 km apart, use Euclidean distance, perhaps with correction for higher latitudes. You can call it keeping it simple or saving computation time, either way, many **experts on the subject would argue that in for shorter distances (< 20 ~ 30 km) your Earth is flat**. Spherical distance calculations like the Haversine distance calculation are more accurate, however they do require more computation time and conversion of the correct spherical coordinates into radians etc.

In another post, we will show you **where taking the curvature of the Earth into consideration is in fact important** and worth the computation time and understanding of coordinate conversions and geometry (i.e. longer distances, flight paths, real-time navigation apps). We will also who you how to build a quick **location based app in Swift in under 10 minutes** and test it on your own iOS device and/or simulator.

Please feel free to comment,** share this post** and also **share results of your own distance calculations.**

Also please feel free to visit sources, cited below; consulted for sample code, graphics and expertise on geodesics, great circles, flat-Earth and spherical Earth distance calculations, **GIS** and **LBS** app programming in **Python**. Also check out a similar post on **great circles and geodesics** at **geoidlife.com**.

**Sources**:

“Calculating Geographic Distance: Concepts and Methods”: Frank Ivis, Canadian Institute for Health Information, Toronto, Ontario, Canada; https://www.lexjansen.com/nesug/nesug06/dm/da15.pdf

“Distance on a sphere: The Haversine Formula”: Blog Post created by Simon Kettle on Oct 5, 2017; https://community.esri.com/groups/coordinate-reference-systems/blog/2017/10/05/haversine-formula

“What is the best way to calculate the great circle distance (which deliberately ignores elevation differences) between 2 points?”: Robert G. Chamberlain of Caltech (JPL): rgc@solstice.jpl.nasa.gov and reviewed on the comp.infosystems.gis newsgroup in Oct 1996; http://www.movable-type.co.uk/scripts/gis-faq-5.1.html

“Haversine Formula”: R.W. Sinnott, “Virtues of the Haversine”, Sky and Telescope, vol. 68, no. 2, 1984, p. 159); Cited on: http://www.movable-type.co.uk/scripts/gis-faq-5.1.html

“Geographic distance can be simple and fast”: Joni Salonen, “The Mindful Programmer”: http://jonisalonen.com/2014/computing-distance-between-coordinates-can-be-simple-and-fast/

Fotheringham, A. S., Brunsdon, C., & Charlton, M. (2000). “Quantitative Geography.” London: Sage.