# is Your smartphone a flat-Earther?

At distances of 30km or less, most mobile applications are calculating distance based on a flat, or two-dimensional representation of, Earth. When 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 save mobile application developers computation and complexity during runtime; potentially shaving off seconds on loading times in the location based app you use on a daily basis. A depiction of consequences a flat Earth would have for navigators in the 1500s and 1600s

We are talking about two-dimensiaonal “representations” of our planet Earth; and no, this blog post is NOT suggesting the Earth is actually flat. High school geography may have taught you the Earth is in fact a form of sphere, closer to an imperfect ellipsoid which Earth scientists and geographers call 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 which is closer to a true representation to its shape than any 2d representation such as a paper or digital map. At some point you realized the Earth is, in fact, a curved and complex shape, including all high and low points we have come to know or seen through photography or television.

Putting the globe aside for a moment, it is 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 (where straight line distance will provide only a small error, less than 1/10 of a mile)

## 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 or .019 miles) for latitudes less than 70 degrees
less than 20 meters ( 66 ft or .012 miles) for latitudes less than 50 degrees
less than 9 meters ( 30 ft or .005 miles) 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 involved by using straight-line distance. Distance in most apps is denoted in units of 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), and at a lower latitudes, 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 actually appear, or looking for parking, anywhere from .5 to .25 km away. In the following, I will show a correction to straight line distance 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 are 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%, only surpassing 1% error in distance at 89 degrees latitude. Eighty-nine degrees latitude in the Northern hemisphere is the North Pole (very few location-based app users live here)

–(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 a somewhat negligible error at a typical user’s range and use case. Using straight line or Euclidean distance uses your location in a 2d way; 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.

## 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:

“An urban area, where the goal is to calculate the distance between customers’ homes and various retail outlets. In this situation, distance takes on a more specific meaning, usually street distance, making straight line distance less suitable. Since streets in many cities are based on a grid system, the typical trip is 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 let’s 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, distance is 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 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, 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”)

Haversine distance formula below, 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 explains many of the variables used in 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 equal to the distance between point “A” and “B,” source and destination respectively. “O” as the center of the Earth. Segments “OC”, “OB” & “OA” all are equal to the radius of Earth.

The code snippet below in Python has a function that calculates 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

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
meters = round(meters, 3)
kilometers = meters / 1000.0 # output distance in kilometers
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 need 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 show 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.

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

We are living in a world where your "geo-id" is often more useful than your given name. We live on a geoid. We are open to open discussion, the more open the broader the potential for all of us to learn something.

This site uses Akismet to reduce spam. Learn how your comment data is processed.