2009-10-07 46 views
7

我需要使用Rails應用程序中現有的PostGIS數據庫。到目前爲止,我可以很好地訪問數據庫,GeoRuby很好地將'geom'列轉換爲Point對象。從Rails訪問PostGIS空間數據

我在尋找的是在這些表上執行類似ActiveRecord的查詢的簡單方法,例如,

Poi.find_within_radius(...) 

或類似的空間查詢如距離計算等。人。

我嘗試了geokit的幾種組合,附帶的rails插件,但是我確定在ruby/rails宇宙中必須有更好的東西。任何提示?

回答

6

既然你已經有了GeoRuby,把你的POI模型

SRID = 4326 #WGS84 

# geometry column is geom 
# pt is a GeoRuby Point 
def self.find_within_radius(pt, dist = 0.01) 
    self.all :conditions => "ST_DWithin(geom, ST_GeomFromText('POINT(#{pt.x} #{pt.y})', #{SRID}), #{dist})" 
end 

距離計算,你可以使用點方法的對象

dist_circle = poi1.geom.spherical_distance(poi2.geom) 
dist_projected = poi1.geom.euclidean_distance(poi2.geom) 
+0

感謝一堆樣品,我試了一下,他們的工作就像一個魅力!現在我已經有了一個開始做更多的研究(或涉足我的案例......) – Lakitu 2009-10-09 13:30:03

0

ST_Distance()不意味着你可能沒有安裝postgis,或者您沒有創建postgis模板...或者如果模板存在,您沒有使用postgis模板創建數據庫。

1

添加到synecdoche's answer,在Rails 3中,您可以使用ActiveRelation範圍,這將允許您鏈接查詢。

未經測試:

# Poi.rb 

scope :within, proc { |point, distance| 
    p = "POINT(#{point.x} #{point.y})" 
    where("ST_DWithin(geom, ST_GeomFromText('#{p}', #{SRID}), #{distance})") 
} 

scope :rated, proc { |rating| where(rating: rating) } 

用法:

home = Point.new(5,5) 
Poi.rated(5).within(home, 25) 

即使你不這樣做連鎖範圍,其中大部分是比使用類的方法更好的時間。