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として球面で測定します。
![]() | |
3次元ジオメトリではST_3DDWithinを使います。 |
![]() | |
この関数の呼び出しによって、ジオメトリで使用可能なインデクスを使用したバウンディングボックスの比較が自動的に行われます。 |
このメソッドはOGC Simple Features Implementation Specification for SQL 1.1の実装です。
Availability: 1.5.0 ジオグラフィが導入されました。
Enhanced: 2.1.0で、ジオグラフィでの速度が向上しました。詳細についてはMaking Geography fasterを参照して下さい。
Enhanced: 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);