Haversine

Nick
2 min readJun 1, 2013

So recently I’ve been writing a lot of JavaScript and with that has come an unhealthy obsession with Node. I have always found the best way to learn something is to do it. So I have been giving myself little projects and creating them in Node to help expand my brain.

I had a random thought to create something that works with the proximity of the users. Geolocating is easy enough these days with navigator.geolocation.getCurrentPosition, so that is not much of a challenge and of course has nothing to do with Node. Essentially my idea is to allow two users to communicate with each other based on their proximity to each other. This would prevent people who were not close enough to each other to not see each others messages.

In HTML5 navigator.geolocation.getCurrentPosition returns the latitude and longitude of a given user. In order for my application to work correctly I need to calculate the distance of the users and then go from there. The thought process is essentially grabbing the user’s position on the client side, sending it over the server (Node) and storing it. Then with this information I am able to check iterate through the users prior to sending a message about and then check compare their locations with the lovely haversine formula. Prior to working on this project I had never really used the formula before but it’s a pretty simple process and has been around for a long time and is as follows:

a = sin²(Δφ/2) + cos(φ1).cos(φ2).sin²(Δλ/2)
c = 2.atan2(√a, √(1−a))
d = R.c

So converting this into JavaScript did not serve as much of a challenge due to the fact that there are tons of versions available on the web. With some tweaking of the code I was able to create a haversine function that worked to my liking which I ended up packaging it up and serving it as my first contribution to npm.

Thus far my Node journey has been great. Coming from creating web applications in Django, I find that I am able to accomplish things a lot quicker and with much less code. Nothing against Django and Python, but I’m having much more fun this way.

--

--