Calculating distance using geo coordinates in ruby
As the social part of the sites is growing stronger, everyone of us has to include a user’s location of some sort into the application. There can be many reasons for that, be it location based search, advertising or something else unrelated. But mark this, you will have to deal with locations in the future.
I won’t get into the details of how to get the user’s latitude and longitude, but geocoder gem could be helpful for you. I have found one JavaScript solution with the descriptions of what are the different implementations of the calculation and which one is more correct so
I won’t get into the explanation. You can check the explanation and even more
stuff you can do with 2 geo coordinates on the Movable Type Scripts
The distance can be calculated using 3 formulas, Haversine, Spherical
Law of Cosines, and Equirectangular approximation
The prerequisites we will need are degree to radian conversion which is easily
done with degree / 180 * Math::PI
, but to make the code easier to write we
can monkey patch the Float with to_rad method which will calculate this for
us. We could use refinements, or make a method object and not pollute the
global space but we can leave it like this for now.
After we have done the prerequisites let’s assume that we have two objects,
and each one has a latitude and a longitude. For the sake of this post we can
make them a hash with two keys latitude
and longitude
. And we take the
earth radius as 6371km
As you can see by calling the distance method with all 3 parameters, each one
will produce a slightly different result. As they say, the haversine
one
should be the most accurate, but take caution. I would like to benchmark them
some day and see which one calculates the result faster.
Thanks to Movable Type Scripts for providing the JavaScript code and all the insight. I just did a rewrite in Ruby.
Comments