Roughly a year ago, I wrote a post about how to sort a list of physical locations by how close they are to you. At the time, I was working on an app that needed to know how close you were to each of Wisconsin's State Parks. On July 26, I am giving an online presentation at That Conference on the topic of "Locating your user in meatspace" and ahead of that, I wanted to drill down on the topic of how to calculate the distance between two point while only using math to do so.
So, how do you do that? You use the Haversine formula. Now, I am not a great mathematician according to Simon Kettle:
The haversine formula is a very accurate way of computing distances between two points on the surface of a sphere using the latitude and longitude of the two points. The haversine formula is a re-formulation of the spherical law of cosines, but the formulation in terms of haversines is more useful for small angles and distances.
According to Kettle, the word "Haversine" comes from the function: haversine(θ) = sin²(θ/2). The formula can be used in javascript code like so:
The output is in kilometers but since 1 kilometer is equal to 0.621371 miles, it should be reasonably easy to convert the output to miles.
So, what do you think? How are you going to use the haversine formula in your projects? Feel free to let me know in the comments, below.
Top comments (0)