我正在使用 DataMapper 管理具有按纬度和经度定位的兴趣点 (POI) 的数据库。我想做一个查询并找到给定纬度和经度 x 距离内的所有 POI。例如,纬度 45、经度 90 1000m 范围内的所有 POI。
我设置了这个:
class POI
include DataMapper::Resource
property :id, String, :key => true
property :title, String, :required => true
property :lat, Float, :required => true
property :lon, Float, :required => true
def distance(latitude, longitude)
# Taken from https://github.com/almartin/Ruby-Haversine
earthRadius = 6371 # Earth's radius in km
# convert degrees to radians
def convDegRad(value)
unless value.nil? or value == 0
value = (value/180) * Math::PI
end
return value
end
deltaLat = (self.lat - latitude)
deltaLon = (self.lon - longitude)
deltaLat = convDegRad(deltaLat)
deltaLon = convDegRad(deltaLon)
# Calculate square of half the chord length between latitude and longitude
a = Math.sin(deltaLat/2) * Math.sin(deltaLat/2) +
Math.cos((self.lat/180 * Math::PI)) * Math.cos((latitude/180 * Math::PI)) *
Math.sin(deltaLon/2) * Math.sin(deltaLon/2);
# Calculate the angular distance in radians
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
distance = earthRadius * c
return distance
end
end
我希望能够通过类似于以下的调用找到记录:
pois = POI.all(distance(45,90).lte => 1000)
但这给出了一个错误:
./poi-provider.rb:44:in `<main>': undefined method `distance' for main:Object (NoMethodError)
我阅读了 dkubb 的关于在方法中定义复杂查询的答案,但这是不同的,因为我需要传入参数并且我试图将该方法用作条件。
我该怎么做——或者,有没有更好的方法来使用 DataMapper 来查找给定纬度和经度附近的点,而不会崩溃并且只使用原始 SQL?