5
4

More than 5 years have passed since last update.

PostGISで多角形内にある点を探す

Last updated at Posted at 2019-05-14

はじめに

PostGISってなに?、環境構築?から1歩進んで、実際にPostGISを試す流れを紹介します。

環境

以下の記事を参考にDocker環境を構築します。
dockerでPostGISを入れたPostgreSQL環境構築

多角形内にある点を探す

※以下は、先の参考記事のファイル名やデータベース構成を元に作成しています。

検索対象となる点を登録します

対象となる点は、緯度経度を示す点を 3 x 3 のマトリクスとします。

緯度経度 133 134 135
35 POINT(133, 35) POINT(134, 35) POINT(135, 35)
34 POINT(133, 34) POINT(134, 34) POINT(135, 34)
33 POINT(133, 33) POINT(134, 33) POINT(135, 33)
insert
INSERT INTO test_table (gid, geom) VALUES
(1, ST_GeomFromText('POINT(135 35)', 4612)),
(2, ST_GeomFromText('POINT(135 34)', 4612)),
(3, ST_GeomFromText('POINT(135 33)', 4612)),
(4, ST_GeomFromText('POINT(134 35)', 4612)),
(5, ST_GeomFromText('POINT(134 34)', 4612)),
(6, ST_GeomFromText('POINT(134 33)', 4612)),
(7, ST_GeomFromText('POINT(133 35)', 4612)),
(8, ST_GeomFromText('POINT(133 34)', 4612)),
(9, ST_GeomFromText('POINT(133 33)', 4612));

抽出条件となる多角形は?

先の 3 x 3 のマトリクスから中央のPOINT(134, 34)を抽出するとして、それを囲む多角形を定義します。

抽出イメージ

Screen Shot 2019-05-15 at 8.37.26.png

抽出対象の点

緯度経度 133 134 135
35
34 POINT(134, 34)
↑これを抽出したい
33

抽出条件となる多角形

「◇」みたいなひし形をイメージしています

緯度経度 133 134 135
35 POINT(134, 35)
34 POINT(133, 34) POINT(135, 34)
33 POINT(134, 33)

検索クエリ

select
SELECT
  gid,
  ST_Astext(ST_Transform(geom, 4612))
FROM test_table
WHERE ST_Contains(
    ST_Transform(
      ST_GeomFromText('POLYGON((135 34, 134 35, 133 34, 134 33, 135 34))', 4612),
      4612
    ),
    geom
  );

※読み方

  • ST_Astext(ST_Transform(geom, 4612))
    • geomフィールドを、空間参照系識別コード(SRID)を4612:JGD2000(地理座標系)に変換して、テキストに変換します。
  • ST_Contains(A, B)
    • Aに含まれるBを探す
  • ST_GeomFromText('POLYGON((135 34, 134 35, 133 34, 134 33, 135 34))', 4612),
    • 始点と終点が同じある輪で囲まれた多角形を示すテキストを、4612:JGD2000(地理座標系)に変換します。

検索結果

Screen Shot 2019-05-15 at 8.29.01.png

想定した値が返ってきましたね!

蛇足

ST_Astext(ST_Transform(geom, 4612))の個所を
ST_Transform(geom, 4612)とすると
Screen Shot 2019-05-15 at 8.29.19.png
何を言っているかさっぱり

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4