从Rails访问PostGIS空间数据

Lak*_*itu 7 postgis ruby-on-rails spatial

我需要使用Rails应用程序中的现有PostGIS数据库.到目前为止,我能够很好地访问数据库,GeoRuby很好地将'geom'列转换为Point对象.

我正在寻找的是一种在这些表上执行类似ActiveRecord的查询的简单方法,例如

Poi.find_within_radius(...)
Run Code Online (Sandbox Code Playgroud)

或类似的空间查询,如距离计算等.人.

我尝试了几种geokit组合,附带了rails插件,但我确信在ruby/rails宇宙中必须有更好的东西.任何提示?

syn*_*che 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
Run Code Online (Sandbox Code Playgroud)

对于距离计算,您可以使用点对象上的方法

dist_circle = poi1.geom.spherical_distance(poi2.geom)
dist_projected = poi1.geom.euclidean_distance(poi2.geom)
Run Code Online (Sandbox Code Playgroud)