DataMapperを使用して、緯度と経度で特定されたPOI(Points)を持つデータベースを管理しています。クエリを実行して、指定された緯度と経度の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を使用することなく、特定の緯度と経度の近くのポイントを見つけるためのより良い方法はありますか?