> ## Content Index
> Fetch the complete content index at: https://blog.anthea.day/llms.txt
> Use this file to discover other available public pages before exploring further.

# 歡迎來到 GIS 的世界－Day 18：PostgreSQL 和 PostGIS
- URL: https://blog.anthea.day/series-2022-ithome-18/
- Published: 2022-10-01T16:19:58.000Z
- Updated: 2026-11-06T19:22:05.000Z
- Author: Anthea / 芫荽
- Tags: #Migrated-1792241843742, #Import 2026-10-17 12:57, Coding, 2022 iThome 鐵人賽：歡迎來到 GIS 的世界

安裝完成之後，就可以開始我們的 PostgreSQL 之旅了。首先找到我們的 pgAdmin4：

![](https://cdn-images-1.medium.com/max/800/0*TPdP3JF8Gvi9uvWf.png)

打開之後應該會要求你輸入一個 Master Password，要注意這個和我們在安裝過程中所輸入的密碼不同，剛剛所輸入的是連線到 localhost database 的密碼，現在這個是登入到 pgAdmin4 的密碼：

![](https://cdn-images-1.medium.com/max/800/0*VdBSfh4kPtnUuI_m.png)

進入之後左側的 Servers 會存放你儲存的連線資訊，這次安裝的是版本 14.X，所以雙擊 PostgreSQL 14 之後會出現另外一個輸入密碼的提示，也就是在安裝過程中所輸入的密碼：

![](https://cdn-images-1.medium.com/max/800/0*6uCVfw8qyS-s3LA9.png)

進入之後應該只會看到預設建立的 postgres 資料庫，這時候可以對著 Databases 這個屬性右鍵，選擇 Create > Database，輸入完名稱之後就能建立一個全新的資料庫了。

#### 使用 PostGIS

我們可以從這兩個地方開始一個新的查詢：

![](https://cdn-images-1.medium.com/max/800/0*i8_sAJePm7XO4IWe.png)

PostGIS 是一種可選擇是否啟用的 Plugin，在建立全新的資料庫時，預設是不會啟用的，所以在使用之前需要另外使用指令來開啟他：

```SQL
-- 注意在 PostGIS 的官網中有特別提到： 
-- DO NOT INSTALL it in the database called postgres.

CREATE EXTENSION postgis;
```

在 db\_with\_postgis 下了指令啟用 PostGIS 之後，可以看到他的 Functions 和 db\_without\_postgis 的數量差異，這樣就代表 PostGIS 啟用成功了：

![](https://cdn-images-1.medium.com/max/800/0*ejIlliV17UBvHtIK.png)

### 常用 Function

PostGIS 的 Function 開頭都是 `ST_`，完整的指令使用方法可以參考PostGIS 的[官方文件](https://postgis.net/docs/manual-dev/reference.html?ref=blog.anthea.day#idm9544)，這裡就選幾個常用的來介紹：

#### ST\_AsText

將 PostgreSQl 中，型別為 geometry 的資料轉換成 WKT 的格式：

![](https://cdn-images-1.medium.com/max/800/0*baQNbkjx6ormxPiH.png)

#### ST\_GeomFromText

將 WKT 文字轉換成 geometry 型別：

![](https://cdn-images-1.medium.com/max/800/0*M8VU_nx0cD8fIdI2.png)

#### ST\_Transform

轉換 geometry 的座標系統：

![](https://cdn-images-1.medium.com/max/800/0*eqyhOy9hbcei6jEq.png)

#### ST\_Within

`ST_Within(A, B)` 會去判斷 A 是否被包含在 B 中：

![](https://cdn-images-1.medium.com/max/800/0*FAnvkxsuqjV_K9xl.png)

#### ST\_Contains

`ST_Contains(B, A)` 會去判斷 B 是否包含 A：

![](https://cdn-images-1.medium.com/max/800/0*lmG8wqPStN11OBX3.png)

這兩個 Function 關係會是 `ST_Within(A,B)` \= `ST_Contains(B,A)`，要注意在使用上不要混淆了。

#### References

- [PostGIS](https://postgis.net/?ref=blog.anthea.day)
- [PostGIS Docs](https://postgis.net/docs/?ref=blog.anthea.day)