0

我正在使用 Geokit 插件来计算 current_user 和其他用户之间的距离(地理编码实际存储在 Profile 模型中)。

出于测试目的,我创建了两个用户,一个在明尼苏达州明尼阿波利斯,一个在明尼苏达州圣保罗。我使用 Geokit gem 在 IRB 会话中对 Profiles 的 lat/lng 对进行地理编码。

我更改了索引视图以列出每个配置文件的名称、位置和纬度/经度对。这些值与数据库中的值匹配。

我更改了索引视图以显示 current_user 的 lat/lng 对。我作为每个用户进行了身份验证,以确保 current_user 的 lat/lng 对符合预期。它做了。

我向 Profile 模型添加了一个名为 ll 的实例方法,以将 lat/lng 字段作为 LatLng 对象返回:

def ll
  #if lat and lng fields aren't empty
  LatLng.new(self.lat,self.lng) if (!self.lat.nil? && !self.lng.nil?)
end

我更改了 ProfileController 的 Index 操作中的查询来计算每个用户与 current_user 之间的距离:

@profiles = Profile.find(:all,
  :conditions => conditions,  # set WHERE clause
  :order => order_by, # set ORDER BY clause
  :origin => current_user.profile.ll,  # calculate distance based on current_user's location
  :units => :miles  # use miles

最后,我更改了 Index 视图以显示 current_user 和每个单独用户之间的距离:

<%=h profile.location %> (<%= profile.ll %>) -
<%= profile.distance.to_f.round(1) %> mi

当我作为用户 A (44.9799654,-93.2638361) 进行身份验证时,距离计算是正确的:

A (44.9799654,-93.2638361) - 0.0 英里 B (44.9444101,-93.0932742) - 8.7 米

但是,当我以用户 B (44.9444101,-93.0932742) 身份进行身份验证时,距离计算不正确:

A (44.9799654,-93.2638361) - 32.8 英里 B (44.9444101,-93.0932742) - 41.1 英里

我能够验证“原始”纬度/经度对之间的距离计算:

a = LatLng.new(44.9799654,-93.2638361)
=> #<Geokit::LatLng:0x1034af778 @lat=44.9799654, @lng=-93.2638361>
>> b = LatLng.new(44.9444101,-93.0932742)
=> #<Geokit::LatLng:0x1034aab88 @lat=44.9444101, @lng=-93.0932742>
>> a.distance_to(b)
=> 8.70261379563918
>> b.distance_to(a)
=> 8.70261379563918

我无法解释正在发生的事情。任何想法,将不胜感激。

4

1 回答 1

1

如果你这样做会发生什么:

 @profiles = Profile.find(:all,
  :conditions => conditions,  # set WHERE clause
  :order => order_by, # set ORDER BY clause
  :origin => current_user.profile, # .ll # calculate distance based on current_user's location
  :units => :miles  # use miles

您的错误让我怀疑存在数据舍入/转换问题,并且 :origin 应该能够直接获取 lat 和 lng。您可能还想在调用 Profile.find(...) 之前检查 (logger.debug) 所有涉及的类型

我无法想出一个简单的转换来给出那些特定的错误,但这是我的怀疑。如果这没有帮助,您可以将生成的 sql 添加到输出中吗?基于此,也许可以找出问题所在。

编辑添加:

Craig,要对类型进行调试,请给出:

logger.debug("lat: #{current_user.profile.lat}  #{current_user.profile.lat.class.to_s} lng: #{current_user.profile.lng} #{current_user.profile.lng.class.to_s}")
logger.debug("lat: #{current_user.profile.ll.lat}  #{current_user.profile.ll.lat.class.to_s} lng: #{current_user.profile.ll.lng} #{current_user.profile.ll.lng.class.to_s}")

当您实际遇到错误时尝试一下,然后查看您的 development.log。(注意:该代码中可能存在错误,因为我只是将其输入到窗口中,但您明白了。)否则,您可能应该检查 SQL 查询中显示的内容,因为这将显示 post-字符串转换数字。

于 2010-05-20T22:59:04.470 回答