我正在使用Geokit插件来计算current_user和其他用户之间的距离(地理编码实际上存储在Profile模型中)。
出于测试目的,我创建了两个用户,一个在明尼苏达州的明尼阿波利斯,另一个在明尼苏达州的圣保罗。我使用Geokit gem在IRB会话中对Profiles的lat/lng对进行了地理编码。
我更改了Index视图,以列出每个概要文件的名称、位置和lat/lng对。这些值与数据库中的值匹配。
我更改了Index视图,以显示current_user的lat/lng对。我以每个用户的身份进行了身份验证,以确保current_ User的lat/lng对符合预期。确实是这样。
我向配置文件模型添加了一个名为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的索引操作中的查询,以计算每个用户和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最后,我更改了索引视图,以显示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.7m
但是,当我作为用户B (44.9444101,-93.0932742)进行身份验证时,距离计算是不正确的:
A (44.9799654,-93.2638361) -32.8mB (44.9444101,-93.0932742) -41.1mi
我能够验证“原始”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我不知所措地解释发生了什么。任何想法都将不胜感激。
发布于 2010-05-21 06:59:04
如果您这样做了,会发生什么:
@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。(注意:该代码中可能有一个bug,因为我只是在窗口中输入它,但是您已经明白了。)否则,您可能应该检查一下SQL查询中显示的内容,因为这将显示字符串转换后的数字。
https://stackoverflow.com/questions/2869207
复制相似问题