使用 RoR 和 postGIS 获取附近的点

Get nearby points with RoR and postGIS

我正在尝试获取,给定经度和纬度,return 来自 table(具有 lon 和 lat 属性)的所有记录,这些记录在 1 英里半径内。 我在想我应该用 ST_Dwithin 和 ST_MakePoint 做点什么,但不确定如何使用它。

这是我到目前为止所拥有的:

def get_nearby(longitude, latitude)
  Device.where(ST_DWithin(ST_MakePoint(longitude, latitude, 1.60934)))
end

[更新] 所以,我的最终功能是:

  scope :nearby_devices, ->(lon,lan) { where(
    <<-SQL,
      ST_DWithin(
        ST_SetSRID(ST_MakePoint(longitude,latitude), 4326),
        ST_SetSRID(ST_MakePoint(?, ?), 4326),
        1.60934
      )
    SQL
  lon,lan)}

我的模型有两个浮点属性:longitudelatitude

ST_DWithin's parameters are geometry, geometry, distance, so you're on the right track. Assuming Device has a lat/lon column named coordinates, you need to make a point 的正确类型(可能是 WGS 84)并将其与 coordinates.

进行比较
Device.where(
  <<-SQL,
    ST_DWithin(
      coordinates,
      ST_SetSRID(ST_MakePoint(?, ?), 4326),
      1.60934
    )
  SQL
  longitude, latitude
)

这里是 post 最终版本:这个解决方案让我以米为单位测量距离:

scope :nearby_devices, ->(lon, lat) {
    Device.where( "ST_Distance_Sphere(ST_SetSRID(ST_MakePoint(longitude,latitude), 4326),
      ST_SetSRID(ST_MakePoint(?, ?), 4326)) <= 1609 ", lon, lat)}

希望对大家有所帮助