名稱

ST_DWithin — 測試兩個幾何圖形是否在給定的距離內

概要

boolean ST_DWithin(geometry g1, geometry g2, double precision distance_of_srid);

boolean ST_DWithin(geography gg1, geography gg2, double precision distance_meters, boolean use_spheroid = true);

描述

如果幾何圖形在給定的距離內,則返回 true

對於 geometry:距離是以幾何圖形的空間參考系統定義的單位指定的。為了使此函數有意義,源幾何圖形必須位於相同的坐標系統中(具有相同的 SRID)。

對於 geography:單位為公尺,距離測量預設為 use_spheroid = true。為了更快地評估,請使用 use_spheroid = false 在球體上測量。

[Note]

對於 3D 幾何圖形,請使用 ST_3DDWithin

[Note]

此函數呼叫包含一個邊界框比較,該比較利用幾何圖形上可用的任何索引。

此方法實作了 OGC Simple Features Implementation Specification for SQL 1.1。

可用性:1.5.0 引入了對 geography 的支援

增強功能:2.1.0 提高了 geography 的速度。有關詳細資訊,請參閱 Making Geography faster

增強功能:2.1.0 引入了對曲線幾何圖形的支持。

在 1.3 之前的版本中,ST_Expand 通常與 && 和 ST_Distance 一起使用來測試距離,在 1.3.4 之前的版本中,此函數使用了該邏輯。從 1.3.4 開始,ST_DWithin 使用更快的短路距離函數。

範例

-- Find the nearest hospital to each school
-- that is within 3000 units of the school.
--  We do an ST_DWithin search to utilize indexes to limit our search list
--  that the non-indexable ST_Distance needs to process
-- If the units of the spatial reference is meters then units would be meters
SELECT DISTINCT ON (s.gid) s.gid, s.school_name, s.geom, h.hospital_name
  FROM schools s
    LEFT JOIN hospitals h ON ST_DWithin(s.geom, h.geom, 3000)
  ORDER BY s.gid, ST_Distance(s.geom, h.geom);

-- The schools with no close hospitals
-- Find all schools with no hospital within 3000 units
-- away from the school.  Units is in units of spatial ref (e.g. meters, feet, degrees)
SELECT s.gid, s.school_name
  FROM schools s
    LEFT JOIN hospitals h ON ST_DWithin(s.geom, h.geom, 3000)
  WHERE h.gid IS NULL;

-- Find broadcasting towers that receiver with limited range can receive.
-- Data is geometry in Spherical Mercator (SRID=3857), ranges are approximate.

-- Create geometry index that will check proximity limit of user to tower
CREATE INDEX ON broadcasting_towers using gist (geom);

-- Create geometry index that will check proximity limit of tower to user
CREATE INDEX ON broadcasting_towers using gist (ST_Expand(geom, sending_range));

-- Query towers that 4-kilometer receiver in Minsk Hackerspace can get
-- Note: two conditions, because shorter LEAST(b.sending_range, 4000) will not use index.
SELECT b.tower_id, b.geom
  FROM broadcasting_towers b
  WHERE ST_DWithin(b.geom, 'SRID=3857;POINT(3072163.4 7159374.1)', 4000)
    AND ST_DWithin(b.geom, 'SRID=3857;POINT(3072163.4 7159374.1)', b.sending_range);

        

另請參閱

ST_DistanceST_3DDWithin