Aniket Shivam Tiwari Aniket Shivam Tiwari - 5 months ago 13
Ruby Question

Haversine is not giving me correct result

I am trying to calculate distance between two points in kilometers but it is giving me wrong.


location.each do |loc|
distance = Haversine.distance(28.6139, 77.209, loc[:lat].to_f, loc[:long].to_f).to_km
puts " #{distance}"
end




Here is the distance which I am getting and which is wrong


7385.99072855455
7383.795725224046
7392.13122601482
7391.537885880786




The data of the location is in my database


[{"id":1,"lat":28.6139,"lng":77.209,"location":"","object_id":1,"created_at":"2016-06-07T05:46:53.000Z","updated_at":"2016-06-07T05:46:53.000Z","object_type":"abc"},{"id":2,"lat":28.6692,"lng":77.4538,"location":"","object_id":2,"created_at":"2016-06-07T05:49:23.000Z","updated_at":"2016-06-07T05:49:23.000Z","object_type":"cde"},{"id":3,"lat":28.4595,"lng":77.0266,"location":"","object_id":3,"created_at":"2016-06-07T05:50:22.000Z","updated_at":"2016-06-07T05:50:22.000Z","object_type":"ggg"},{"id":4,"lat":28.4744,"lng":77.504,"location":"","object_id":4,"created_at":"2016-06-07T05:50:24.000Z","updated_at":"2016-06-07T05:50:24.000Z","object_type":"eerr"}]

Answer

You have a typo: loc[:long] instead of loc[:lng], the line should read:

Haversine.distance(28.6139, 77.209, loc[:lat].to_f, loc[:lng].to_f).to_km

You passed nil.to_f as _longitude of the second point. This is equivalent to passing 0

Comments