Mongoid,以公里为单位获取与模型的距离

Mongoid, get distance from models in kilometers

我有模型 Shop,它有这个地理定位字段:

 class Shop
   include Mongoid::Document
   field :location, type: Array

   index( { location: '2d' }, { min: -180, max: 180 })
   before_save :fix_location, if: :location_changed?
   def fix_location
    self.location = self.location.map(&:to_f)
   end
 end

我已经为我的模型创建了索引。

那我想找50公里左右的店铺:

  distance = 50 # km
  loc = [lat, lng]

  Shop.where(location: {"$near" => loc , "$maxDistance" => distance.fdiv(111.12)})

此方法工作正常,并提供了我需要的模型。但是,如何确定他们离我的位置有多远(以公里为单位)?

我需要使用聚合吗?

由于 MongoDB $near 运算符已经按距离对文档进行排序,您可以简单地计算 Rails 服务器中查询返回的每个文档的距离,例如使用 the Haversine gem.

distance = 50 # km
loc = [lat, lng]
loc_lng_lat = [lng, lat]
Shop.where(location: {"$near" => loc_lng_lat , "$maxDistance" => distance.fdiv(111.12)}).each do |shop|
    shop_lat_lng = [shop.location[1], shop.location[0]]
    distance = Haversine.distance(loc, shop_lat_lng)
    # do what you want with the distance
end

注意纬度和经度的交换,因为 MongoDB 期望 2D 地理数组采用 [longitude, latitude] 格式,而 Haversine gem 期望 [latitude, longitude]