Search code examples
ruby-on-railsjsonhaversine

Haversine formula in ruby


I need to calculate distance between the latitudes and longitudes obtained from json with the lats and longs inside distance method

I am getting error distance': undefined method-' for "12.986375":String (NoMethodError)

    require 'json'
class Numeric
    def to_rad
      self * Math::PI / 180
    end
  end

  def distance( lat2,  lon2)
     lat1=12.9611159
     lon1=77.6362214
     dLat = (lat2-lat1).to_rad;
     dLon = (lon2-lon1).to_rad;
     a = Math.sin(dLat/2) * Math.sin(dLat/2) +
         Math.cos(lat1.to_rad) * Math.cos(lat2.to_rad) *
         Math.sin(dLon/2) * Math.sin(dLon/2);
     c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
     d = 6371 * c; 
     puts d
  end

file= File.read('customers.json')
data_hash= JSON.parse(  file)

data_hash["customers"].each do |user|
  latitude=user["latitude"]
  longitude=user["longitude"]
  distance(latitude,longitude)
end 

Below is my json file from which lats and longs are taken.

{"customers" :[

            {"latitude": "12.986375", "user_id": "12", "name": "Chris", "longitude": "77.043701"},
            {"latitude": "11.92893", "user_id": "1", "name": "Alice", "longitude": "78.27699"},
            ]
}

Solution

  • error is quite self explanatory - your json keeps latitude/longitude as strings. parse them to float before calling distance method

    latitude=user["latitude"].to_f
    longitude=user["longitude"].to_f
    distance(latitude,longitude)