使用 Ruby 地理编码器检索附近的用户和 return 距离

Using Ruby Geocoder for retrieving nearby users and return distance

是否可以使用 Geocoder 检索某个半径内附近的用户,并使其 return 成为距离计算的结果而无需重复显示?

例如,假设我们使用这个(在 Rails 应用程序中):

User.near(@me, 10, units: :km)

它将return一个ActiveRecord::Relation与用户@me10公里以内的所有用户。

如果我现在想显示一个包含所有 returned 用户及其到 @me 的距离的列表,我是否需要使用 distance_to 逐一重新计算距离,或者是否有一种方法可以使 Geocoder return 在添加的模型属性中计算距离(例如)?

When you run a location-aware query the returned objects have two attributes added to them:

User.near(@me, 10, units: :km).each do |user|
  puts "#{user.name} is #{user.distance} clicks to the #{user.bearing}"
end

我正在使用这个嵌入式 Ruby 版本的逻辑,这在逻辑上与上面@maxcal 给出的答案相似。我将其包括在内是因为下面的跟踪与此代码有关。

<% for location in @location.nearbys(20) %>
  <li> <span class="badge"><%= location.distance.round(2) %> miles</span> from here you'll find <strong>
  <%= link_to location.name, location %> </strong> at <%= location.full_address %>.</li>
<% end %> 

但是,我认为答案是 Geocoder 正在为符合要求的记录集创建临时数据存储。 .distance 是关键变量。

如果我查看跟踪,它会显示初始数据库命中,但不会显示循环中每个项目的后续命中。可以查看 Geocoder 代码并确认,但痕迹似乎是决定性的。

  [1m[36m (0.0ms)[0m  [1mSELECT COUNT(*) FROM "reviews" WHERE "reviews"."user_id" = [0m  [["user_id", 8]]
  Rendered shared/_user_posted_badge.html.erb (15.6ms)
// Comment Geocoding starts here
  Rendered locations/_map_show.html.erb (0.0ms)
  [1m[35mLocation Load (0.0ms)[0m  SELECT locations.*, 3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((30.267153 - locations.latitude) * PI() / 180 / 2), 2) + COS(30.267153 * PI() / 180) * COS(locations.latitude * PI() / 180) * POWER(SIN((-97.7430608 - locations.longitude) * PI() / 180 / 2), 2))) AS distance, MOD(CAST((ATAN2( ((locations.longitude - -97.7430608) / 57.2957795), ((locations.latitude - 30.267153) / 57.2957795)) * 57.2957795) + 360 AS decimal), 360) AS bearing FROM "locations" WHERE (locations.latitude BETWEEN 29.977689433778306 AND 30.556616566221695 AND locations.longitude BETWEEN -98.07821040202988 AND -97.40791119797011 AND (3958.755864232 * 2 * ASIN(SQRT(POWER(SIN((30.267153 - locations.latitude) * PI() / 180 / 2), 2) + COS(30.267153 * PI() / 180) * COS(locations.latitude * PI() / 180) * POWER(SIN((-97.7430608 - locations.longitude) * PI() / 180 / 2), 2)))) BETWEEN 0.0 AND 20 AND locations.id != 65)  ORDER BY distance ASC
// Geocoding section complete
  [1m[36mPhotograph Exists (0.0ms)[0m  [1mSELECT  1 AS one FROM "photographs" WHERE "photographs"."location_id" =  LIMIT 1[0m  [["location_id", 65]]
  [1m[35mPhotograph Load (0.0ms)[0m  SELECT "photographs".* FROM "photographs" WHERE "photographs"."location_id" =   ORDER BY "photographs"."created_at" DESC  [["location_id", 65]]