【问题标题】:Get nearby points with RoR and postGIS使用 RoR 和 postGIS 获取附近的点
【发布时间】:2016-01-04 14:52:34
【问题描述】:

我试图在给定经度和纬度的情况下,返回半径为 1 英里的表(具有 lon 和 lat 属性)中的所有记录。 我在想我应该用 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

【问题讨论】:

    标签: ruby-on-rails postgis


    【解决方案1】:

    ST_DWithin 的参数是geometry, geometry, distance,所以你在正确的轨道上。假设Device 有一个名为coordinates 的纬度/经度列,您需要使用正确类型(可能是WGS 84)的make a point 并将其与coordinates 进行比较。

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

    【讨论】:

    • 这样可以吗? Device.where(
    • 您需要在这两点上调用 ST_SetSRID 以使它们的类型相同,这样应该可以正常工作
    • 嘿,我应该如何更换?有 lon 和 lan 参数吗?
    • ActiveRecord#where 用您提供的其余参数替换 SQL 字符串中的问号,就像我在示例中所做的那样。查看the Rails guide
    • 这实际上是在归还我所有的设备。不关心我指定的 1.60934 距离。线索?
    【解决方案2】:

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

    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)}
    

    希望对大家有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      相关资源
      最近更新 更多