As you may know I recently released an application named Finicky that allows you to match up locally available items to locations. These locations are stored by their latitude and longitude coordinates. One of the features I wanted to enable was a display of the distance between your current location and the location of each item. To do this you have to do some math on the two pairs of latitude and longitude.

This is evidently a common need, and there is a mathematic formula with a name and everything:

The haversine formula:

a = sin²(^lat/2) + cos(lat1).cos(lat2).sin²(^long/2)

c = 2.atan2(sqrt(a), sqrt(1-a))

d = R.c

This frankly sounds like some sort of experimental drink that pulls a Jekyll and Hyde on you, but instead of making you a monster, makes you upperclass British. But I digress.

One of the cool things about it, is that as written it’s capable of finding distance in whatever measurement you want, as long as you know the radius if the earth in that measure. Very cool, math nerdy stuff.

There is a great bit explaining this, and a version of the haversine formula in JavaScript at Movable Type Scripts. But I had trouble finding an ActionScript version. So I just translated the JavaScript version. It is included below.

https://gist.github.com/1188832.js?file=example.as

### Like this:

Like Loading...

*Related*

I’m a math nerd, and I *love* that the haversine formula exists! Cool stuff.

LikeLike

Math.atan2(Math.sqrt(a), Math.sqrt(1-a))

is the same as

Math.asin(Math.sqrt(a))

LikeLike

Thanks for publishing this. It was extremely helpful!

LikeLike