Ruby on rails Haversine gem:将计算出的距离转换为km

时间:2018-11-14 11:25:18

标签: ruby-on-rails ruby gps haversine

我正在执行一个计算两个gps点之间距离的任务,我想将该距离转换为KM:

def distances
    site     = Site.find params[ :id ]
    stores   = Store.current
    distances = []

    stores.map do |store|
      distance = Haversine.distance(site.address.latitude, site.address.longitude, store.address.latitude, store.address.longitude)
      distances << {
        name: store.name,
        value: distance
      }
    end

    render json: {
      distances: distances.to_json
    }

  end

计算项目示例:

  

store2:5527.654499076738

在haversine gem的文档中,有一种转换方法:distance.to_kilometers,但对我不起作用!有帮助吗?

1 个答案:

答案 0 :(得分:0)

您可能需要在生成的to_kilometers上调用Haversine::Distance方法,否则将使用其to_s方法:

def distances
  site = Site.find params[ :id ]

  distances = Store.current.map do |store|
    {
      name: store.name,
      value: Haversine.distance(
               site.address.latitude,
               site.address.longitude,
               store.address.latitude,
               store.address.longitude
             ).to_kilometers
    }
  end

  render json: {
    distances: distances
  }
end

您真正想要做的是在您的distance_in_km类中添加一个Address ...