我正在执行一个计算两个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,但对我不起作用!有帮助吗?
答案 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
...