Geokit距离计算奇怪

时间:2010-05-19 20:39:08

标签: ruby-on-rails geokit

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

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

我更改了索引视图以列出每个配置文件的名称,位置和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 mi 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英里

我能够验证'raw'lat / lng对之间的距离计算:

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

我无法解释发生了什么。任何想法都将不胜感激。

1 个答案:

答案 0 :(得分: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查询中显示的内容,因为它会显示后字符串转换数字。