2013年6月24日 星期一

Postgre 與 PostGIS 安裝 - on Ubuntu

1. Postgre 安裝
    sudo apt-get install postgresql

2. pgadmin3 安裝,pgAdmin 是 postgre 的 GUI 管理介面
    sudo apt-get install pgadmin3

3. Postgre 的啟動與停止
    sudo /etc/init.d/postgresql start
    sudo /etc/init.d/postgresql stop


4. 安裝時會在OS中,建立 postgres 的使用者
    修改 postgres 密碼:
    a. sudo su postgres -c psql template1
    b. ALTER USER postgres WITH PASSWORD '<***password***>';
    c. sudo passwd postgres

5. PostGIS 安裝
    sudo apt-get install postgresql-9.1-postgis

6. 支援 PostGIS 的 DB 設定
    a. createdb mydb

    b. createlang plpgsql mydb
    c. psql -d mydb -f /usr/share/postgresql/9.1/contrib/postgis-1.5/postgis.sql
    d. psql -d mydb -f /usr/share/postgresql/9.1/contrib/postgis-1.5/spatial_ref_sys.sql
    e. psql -d mydb -f /usr/share/postgresql/9.1/contrib/postgix_comments.sql

7. 建立含地理資訊的欄位
    a. create sequence points_id_seq;
    b. create table points (id integer primary key default nextval('points_id_seq'));
    c. 在 points 表格,增加 location 欄位
        select AddGeometryColumn('points', 'location', 4326, 'POINT', 2);
    d. create index points_location_idx on points using GIST (location);

8. 測試
    // Insert 兩筆測試資料,給定兩個景點的經緯座標
    insert into points(location) values (ST_GeomFromText('SRID=4326;POINT(120.67643 24.17387)'));
    insert into points(location) values (ST_GeomFromText('SRID=4326;POINT(120.68548 24.17207)'));

    //假設insert的兩筆 id 分別為 1, 2
    a. 查詢 id=1 與  id=2 的距離
        select ST_Distance(
            ST_Transform((select location from points where id=1), 900913),
            ST_Transform((select location from points where id=2), 900913)
        ) as distance;

        結果: distance欄位值: 607.7513 公尺


    b. 查詢與 id=1 相距 1000公尺以內的點 (排除掉id=1自己)
        select * from points 
        where ST_Distance(
            ST_Transform(location, 900913), 
            ST_Transform((select location from points where id=1), 900913)
        ) < 1000 and id<>1;



PS.
    SRID 代表:某種空間參考系統的 ID
    (SRID=900913,Google Map 使用,計算單位為公尺,因為 900913 looks like google)


參考:
1. Ubuntu 上安裝 Postgre
2. PostGIS 安裝與設定 - Installing PostGIS 1.5 on PostgreSQL 8.4 on Ubuntu
3. PostGIS 手冊: [PostGIS 1.5] [PostGIS 2.0]

    威吧!!! 就是這麼方便!!!
    (待補...以 groovy 撈點出來......)


沒有留言: