Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic 1. Using PostGis To Manage Your GIS Data

Similar presentations


Presentation on theme: "Topic 1. Using PostGis To Manage Your GIS Data"— Presentation transcript:

1 Topic 1. Using PostGis To Manage Your GIS Data

2 Outline Part1. Brief Introduction of PostGIS and Why do we need it?
Part2. Install PostgreSQL, PostGIS and Tools Part3. Load Data into PostGis Tables and Connect Q-GIS with PostGis Part4. Simple Query Part5. Geometry and Spatial Relations

3 Part1. Brief Introduction of PostGIS and Why we need it?

4 How we store and use our own geometric data
A GIS-data record that we collected by ourselves usually looks like: place name or title Releated metadata: (category, background information, other notes, comments, descriptions. ) GeoReference (longitute and latitue values) Example: Place Name:法鼓山世界教育園區 (DDM World Center for Buddhist Education ) Category: Buddhism, Temples, Eductaion GeoReference: , There are usually highly structured data, therefore, we usually save them in a spreadsheet.

5 An SpreadSheet Example

6 Then, we put them into QGIS
EXCEL -> CSV -> QGIS

7 Disadvantages of spreadsheet (I)
EXCEL(spreadsheet application) is not design for managing large amount data. It doesn’t scale. As the amount of data increases, performance suffers, and the visual interface becomes a liability instead of a benefit. It also has fixed limits on how big a spreadsheet and its cells can be. It lacks data integrity. Because every cell is a unique snowflake, things can get very inconsistent

8 Disadvantages of spreadsheet (II)
It’s not very good for working with multiple datasets in combination. Collaborating and sharing is hard. It’s hard to control versions and have a “master” set of data, especially when many people are working on the same project (Google Spreadsheets fix some of this). EXCEL doesn't support geometric objects, and provides no function for manipulate geometric data.

9 Relational DataBase Management System
We need a better data management tool than EXCEL when the amount of data becomes larger and more complex. Generally speaking, we will use Relational DataBase Management System (RDBMS) to replace EXCEL as the main data management system. The same is true for the development of GIS system.

10 Development of GIS System (I)
Frist Generation GIS: GIS Tools + Data saved in backend proprietary format data file. This architecture lacks of the ability to work with others.

11 Development of GIS System (II)
Second Generation GIS: The backend data become a hybrid architecture. The geometric objects are store in proprietary format data file. Other information are store in a DBMS EX: ESRI shape format, the feature geometry is stored in .shp, .shx, other attributes are stored in .dbf (RDBMS) file.

12 Development of GIS System (III)
Third Generation GIS: The backend data is now saved to a Spatial Database. (ex: ArcGIS, QGIS) Some other advanced data management function provided by a database: Support SQL command, able to cooperate with other system like: web application Concurrency Control: allow multiple users working on the same data set. User Privilege Management Complete Backup solution …..

13 What is Spatial Database
Spatial databases = Traditional RDBMS + modules/Data Type Definitions/functions to store and manipulate spatial objects Defining Spatial data types referring to shapes such as point, line, and polygon; Able to build Multi-dimensional spatial indexing for efficient processing of spatial operations; Built-in Spatial functions, posed in SQL, for querying of spatial properties and relationships.

14 Common Spatial Databases
Oracle Spatial and Graph Based on Oracle Database, Proprietary and very expansive MS-SQL Databse: Proprietary and quite expansive MySQL/mariaDB spatial, opensource PostGIS Based on PostgreSQL, opensource (most recommend) Spatialite Based on sqlite, opensource SpatiaLite is probably the best choice when the project at hand needs a standalone, embedded database. Lets say for example you are building a mobile or desktop application that requires an embedded database.

15 What is PostGIS + = Least version: Least version:

16 Part2. Install PostgreSQL, PostGIS
and Tools

17 Brief Procedure of PostGIS Installation
Install softwares: PostgreSQL 9.6.x PostGIS 2.3.2 pgAdmin III 1.2.2 Perform post-install configuration for MAC/Ubuntu Use pgAdmin3 to connect server Create first spatial Database Activate PostGIS extenation

18 Install PostGIS – windows (1/3)
Install: postgresql windows-x64.exe Set Superuser Password Skip Stack Builder

19 Set Password for "postgres"
Postgres is the default superuser for postgreSQL database. During the installation, you will ask to set the password for postgres. Please remember password of postgres, it is important for following steps.

20 Install PostGIS – windows (2/3)
2. Install: postgis-bundle-pg96x64-setup exe

21 Install PostGIS – windows (3/3)
Extract and Install: pgadmin zip

22 Install PostGIS -- MAC Extract and Install: Postgres-9.6.3.zip
(PostgreSQL PostGIS 2.3.2)

23 Install pgAdmin3 Extract and Install: pgadmin3-1.22.2.zip
Drag to Applications Folder

24 First time open pgAdmin 3
Right Click

25 Configure PostgreSQL Database --MAC
After installing postgresSQL, postGis and pgAdmin, you still need to configure the database before we can really use it. The post-install configuration of postgresSQL in MAC OS system is a bit more complicate than windows and Linux. We need performs following 3 commands under terminal.

26 Post Installation (I) --MAC
Step 0. Run Terminal Step 1a. in order to use the command line tools delivered with Postgres.app, execute the following command in Terminal to configure your $PATH > sudo mkdir -p /etc/paths.d && echo /Applications/Postgres.app/Contents/Versions/latest/bin | sudo tee /etc/paths.d/postgresapp Password is required Step 1b. Close and Restart Terminal

27 Post Installation (II) --MAC
Step 2. Create superuser account: postgres > createuser -s postgres If no error message is shown on the screen, then you succeeded. If you see: createuser: creation of new role failed: ERROR: role "postgres" already exists That is fine, too. But If you see: -bash: createuser : command not found You probably: 1. didn't enter correct command of step1. or 2. forget closing and restarting terminal.

28 Post Installation (III) --MAC
Step 3. execute psql and set password for user postgres > psql Your-account=# \password postgres Enter new password: (password for postgres) Enter it again: (password again) Please remember password of postgres, it is important for following steps. If you see: ERROR: role "postgres" does not exist You didn't create postgres in step 2, leave psql, and run step2 again. Command for exiting psql: Your-account=# \q

29 Install PostGIS -- Ubuntu
Run following command > sudo apt-get install postgis postgresql-contrib pgadmin3 After installation complete, run following command > sudo -i -u postgres psql postgres=# \password Enter new password: Enter it again: postgres=# \quit For setting password of postgres

30 Using pgAdmin III to Connect postgreSQL Server
Windows MAC OS X Ubuntu

31 Register New Server first open pgAdmin, you must Register a new Server
Click here to Register a new Server

32 Register New Server (II)
Name: Local PostgreSQL Host: localhost Password: Password of postgres OK

33 Connect to 「Local postgreSQL」
Click the new "Local PostgreSQL" entry to connect

34 Databases Click "Databases" under Local postgreSQL, you will see a "postgres" databases already existed in your system. We now need to create a Database for this course.

35 Creating a Spatial Databases
Right click the databases entry, you will see a menu pop-up. Click "New Database…" in the popup menu.

36 New Database Diaglog Name: TaiwanBuddhistTemples Owner: postgres OK

37 Explore "TaiwanBuddhistTemples" Database
Select the new TaiwanBuddhistTemples database and open it up to display the tree of objects. You’ll see the public schema under TaiwnBuddhistTemple s > Schema > Public.

38 Activate PostGIS function
Need to run a Query to load the PostGIS spatial extension. Click Selected

39 Running SQL Command CREATE EXTENSION postgis;
Make sure 'TaiwanBuddhistTemples' is selected CREATE EXTENSION postgis; CREATE EXTENSION postgis_topology; Click the Play button in the toolbar (or press F5) to “Execute the Query.”

40 Checking PostGIS Installation
Make sure 'TaiwanBuddhistTemples' is selected SELECT postgis_full_version(); PostGIS_Full_Version: Reports full PostGIS version and build configuration info. Execute the query. You shall see:

41 Part3. Load Data into PostGis Tables and Connect Q-GIS with PostGis

42 Loading Spatial Data into Tables
We have prepared several datasets, the all stored in the dataset folder: D1: Boundary of 368 Taiwanese Towns (shape file) D2: MRT Lines (shape file) D3: Location of MRT Stations (shape file) D4: Population of 368 Taiwanese Towns (Excel) D5: Location of Taiwanese Temples (Excel, with locations) For windows users, please make sure the "DataSet folder" is not stored under the folders with Chinese Characters.

43 Loading Shape Files (Using pgShapeLoader)
Works for Windows/Ubuntu Using pgShapeLoader application Windows 7 Ubuntu: shp2pgsql-gui

44 pgShapeLoader Applicaion
User Name: postgres 1 Password: Password of postgres Database: TaiwanBuddhistTemples 2 Connecting: host=localhost port=5432 user=postgres password='*******' dbname=TaiwanBuddhistTemples Connection succeeded.

45 For D1: Table: Town, SRID: 4326, Encoding: UTF-8
Filed name for Geo-info 2 3 4 Table = Town Set Correct SRID : 4326 Select .Shp file 1 6 Options Import 5 Choose Correct Encoding

46 How to check the imported data
Right Click View Data View Top 100 Rows

47 Loading Shape Files using shp2pgsql command
Works for Ubuntu/MAC OS X It is a Command-Line Tool, called shp2pgsql, it will transform shape files to SQL command. in MAC and ubuntu, please launch "Terminal" again, and execute following command.

48 -s: specify SRID of shape file.
> shp2pgsql -s g geom -W "UTF-8" -c {path_to_.dbf_file} public.Town | pbcopy -s: specify SRID of shape file. -g: specify the name of the field for storing geometric object -W: text encoding of shape file -c : for creating Table {path_to_.dbf_file} : specify the path to the .dbf file public.Town: the name of the table for storing the data of shape file > shp2pgsql -s g geom -W "UTF-8" -c {path_to_.dbf_file} public.Town | xclip -sel clip In ubuntu, you have to install xclip first.

49 The easiest way to get "path to .dbf file" :
1. use "Finder" (in MAC) or "file" (in ubuntu), locate and select .dbf file, 2. Right click and select Copy "{filename}.dbf" 3. Go back to terminal, and execute "paste" Example: > shp2pgsql -s g geom -W "UTF-8" -c Documents\02Dataset\D1\Town.dbf public.Town | pbcopy The SQL commands will be sent to System Clipboard. We then can directly paste into SQL Command window.

50 Execute SQL command to load shape file
Paste into SQL command window, and then execute. Click

51 How to check the imported data
Right Click View Data View Top 100 Rows

52 Practice1 : Import Datasets D1-D3
Please import D2 and D3 with same method to your database.Some details: For D1: Table: Town, SRID: 4326, Encoding: UTF-8 For D2: Table: MRTLines, SRID: 4326, Encoding: Big5 For D3: Table: MRTStaions, SRID: 3826, Encoding: UTF-8

53 About DataSet D1 Boundary of 368 Taiwanese Towns (shape file)
Table Fields: Field Name Data Type Example Value Notes gid integer 1 Unique ID townid character varying (8) V02 towncode character varying (12) countyname 臺東縣 Name of country townname 成功鎮 Name of town towneng character varying (39) Chenggong Township countyid character varying (3) V countycode 10014 geom geometry Geometry object (MultiPolygon)

54 About DataSet D2 MRT Lines (shape file) Table Fields: Field Name
Data Type Example Value Notes gid integer 1 Unique ID mrtid character varying (9) mrtsys character varying (20) 台北捷運系統 Taipei or Kashung mrtcode 板南線 Name of MRT Line mrtplan character varying (1) N Still in plan? updatedate character varying (6) 161117 geom geometry Geometry object (Line)

55 About DataSet D3 Location of MRT Stations (shape file) Table Fields:
Field Name Data Type Example Value Notes gid integer 1 Unique ID landmarkid character varying (13) landmarkco 306 landmarkna character varying (74) 捷運南岡山站-出口1 Name of MRT Station landmarkad character varying (7) address character varying (77) 高雄市岡山區大… Address tel character varying (35) updatedate character varying (6) 161117 geom geometry Geometry object (Point)

56 If you didn't get success with D1-D3
We have something here to help you. In SVS_0615/Backup subfolder, you shall see: D1.tar, D2.tar and D3.tar. You can use them to restore a copy from my database. Use Restore and select the tar file to restore. (see next page)

57 Restore Tables Format Custom or Tar Right Click Filename
Path of Tar File Rolename postgres Restore Restore

58 Display your Data in QGIS
Layer Add Layer Add PostGIS Layer Next Slider New

59 Setup Connection from QGIS to PostGIS
Name: localPostGIS_TBT (Anything you like) Host: localhost Database: TaiwanBuddhistTemples V Username: postgres V Password: Password of postgres OK

60 Connection to PostGIS Connect Select Town Add

61 Quick way to add following PostGIS Laysers
Brower Panel

62 Using Browser Panel Refresh Right Click Add Selected Layer

63 Loading EXCEL like data -- General
Import D4.Population.xlsx Producre: S1. Create an empty table in TaiwanBuddhistTemples Database, with 4 fields (tid, city, town, population) S2. Save .xlsx file to CSV files S3. Use CSV import utility to import the CSV data

64 S1-1 pgAdmin3 – Create Table
Databases > TaiwanBuddhistTemples > Schemas > Public > Tables (right click) > New Table Next Slider New Table

65 S1-2 Create Table -- Assign Table Name
Next Slider Name: Population Columns Owner: postgres Click Columns Table for the next step.

66 S1-3 Define Columns Adding city field, as the instruction in next page
2 Name: tid Data Type: Integer 3 1 OK Add

67 S1-3 Character Varying (5)
Continue Adding other fields, as the instruction in next page 2 Name: city Data Type: Character varying LENGTH: 5 1 3 Add OK

68 S1-4 Define Columns II Next Slider integer character varying (5)
Click Constraints Table for the next step. Next Slider Constraints tid integer city character varying (5) town character varying (5) male integer female integer popultaion integer

69 S1-5 Set Primary Key of the Population Tables
3 Constraints Columns 5b 6b 4 tid 5 Add 6 OK 1 2 Primary Key Add 7 OK

70 CSV (comma spereated )(*.CSV)
S2-1 Save xslx to the CSV Save Excel files to CSV file. It should be simple, but it isn't. The problem is: the CSV file saved by MS EXCEL is only in "BIG-5" encoding, which is not acceptable by postgreSQL CSV import function. CSV (comma spereated )(*.CSV)

71 S2-2.1 Workaround 1. Save to UTF-8 CSV
Solution1: Use other softwares to open excel files and save to "unicode" encoded CSV files. Ex: LiberOffice or Numbers (MAC) Running Export function in Page Select CSV and UTF-8 encoding

72 S2-2.2 Workaround 1. Save to UTF-8 CSV
With LibreOffice Unicode (UTF-8) Text CSV OK Running Savs-as CSV in LiberOffice Select UTF-8 encoding

73 S2-2.3 Workaround 2. Convert Big-5 CSV to Unicode CSV
Using EXCEL to save .xslx into Big5 CSV, and then we transform it to UTF-8 CSV. CSV (comma spereated )(*.CSV)

74 S2-2.4 Workaround 2. Convert Big-5 CSV to Unicode CSV
In Windows, open the big-5 CSV with notepad.exe, and save as "utf-8" Encoding:UTF-8 In MAC, use incov command to transform encoding > iconv -f BIG-5 -t UTF-8 {path_to_Big-5_CSV} > {path_of_UTF-8_CSV}

75 S2-3 Import CSV with postgresSQL CSV importer
Right Click Filename Select the CSV file Format CSV Encoding UTF-8 Misc Options. Header v Delimter , (comma) import import

76

77 Practice2 : Import Datasets D4 and D5
Please import D5 with same method to your database. details: For D5: TableName Temples: Field type NULL Primary Key? id char varying (7) NOT NULL Yes name char varying(25) trait postcode integer longitude real latitude address char varying(50)

78 Transforms longitude and latitude values in "Temples" to Geo-objects
Add a new column "geom" for Geo-object Use SQL command to generate Geo-objects and save it to "geom" fields Columns Right Click Add a new field: Field type geom public.geometry Properties Add

79 Run SQL command to create the Geo-object
Execute following SQL command to create Geometric objects from latitude, longitude values. Click UPDATE "Temples" SET geom = ST_GeomFromText('POINT(' || longitude || ' ' || latitude || ')',4326); UPDATE 5114 Query returned successfully in 1 secs.

80 If you didn't get success with D4,D5
We have something here to help you. In SVS_0615/Backup folder, you shall see: D4.tar, D5.tar You can use them to restore a copy from my database. If the unsuccessful table exists, drop it. Use Restore and select the tar file to restore. (see next page)

81 Practices: Try to import your field work data to postGIS, and visualize them in Q-GIS. (Export CSV from Google DOCs) TableName: Fieldwork Field type Primary Key? site-id character(4) Yes team Integer site-id-team date-of-collection date name-zh char varying(20) name-py char varying(50) latitude real longitude foundation-date integer address char varying(100)

82 Part4. Simple SQL

83 Simple SQL SELECT postgis_full_version();
SQL, or “Structured Query Language”, is a means of asking questions of, and updating data in, relational databases. The first SQL in this workshop: SELECT postgis_full_version();

84 Use SQL to ask questions of the data
Select "TaiwanBuddhistTemples" Database, click "SQL Icon" to start entering SQL command. Click Selected Let Try SELECT * FROM "Population"

85 Basic SQL syntax (I) Case 1: Retrieve data from one Table Select [Field_A, Field_B, Field_C…, *] From TableName * in fieldname means: all fields Example: Retrieving data from Population table, but only city, town and population fields. Select city, town, population From "Population"

86 Practice 1: What is the SQL command for retrieving data from Temples table, but only displaying name, trait, address fields. Select name, ………….. , ………….. From "……………………."

87 Basic SQL syntax (II) Case 2: Retrieve data from one Table with conditions Select [Field_A, Field_B, Field_C…, *] From TableName Where conditions Condition works a filter, only the records matches the conditions will be returned. The most common form of conditions is : Field_X = 'ValueA' ex: city= "New York" Field_Y < NumberA ex: population < 10000 Field_Z >= NumberB ex: male >= 2000

88 Select countyname, townname From "Town" Where countyname = '新北市'
Example: “What are the name of the towns in 新北市?” Select countyname, townname From "Town" Where countyname = '新北市' Practice 2: “What are the name and population of towns in 臺中市?” Table name 使用 Double Quote String 用 Single Quote Select city, town , ………….. From "Population" Where city = '…………….'

89 Select ……………. , ………….., trait From "Temples" Where ………………… = '…………….'
Practice 2: “What are the name and address of templates that are categorized as 道場" Select ……………. , ………….., trait From "Temples" Where ………………… = '…………….'

90 multiple conditions in WHERE clause
You can have multiple conditions in where clause but must you use and/or to combine conditions. Example: “lists templates located in '台中市' (postcode: ) Select * From "Temples" Where postcode >= and postcode <= 40999

91 Select town, population From "………………."
Practice 3: “What are the name of temples that are categorized as 道場/道廟/精舍" Select name, trait From "Temples" Where trait = '道場' or trait = '道廟' or trait = '精舍' “What are the name of towns that have more than in "新北市"? Select town, population From "………………." Where ……. = …….. and ………. >=

92 Aggregate Function in SQL
In SQL, an aggregation function is a function where the values of multiple rows are grouped together as input to form a single value of more significant meaning. Sum(column) : Sum all Non Null values over the column Count(column) : Return number of Non Null values of the column Avg(column): Sum(column) / Count(column) Min(column): Minimum value in the column Max(column): Minimum value in the column

93 Select avg(population) From "Population" Where city='臺北市'
Example: “The average population of the towns in 臺北市" Select avg(population) From "Population" Where city='臺北市' How many temples are located in 台北市? (postcode: ) Select count(*) From "…………………" Where postcode >= ……… and …….. <= …….

94 "GROUP BY" statement in SQL
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns. Example: “What are total population in each city?" Select city, sum(population) From "Population" Group by city

95 Select countryname, count(…………) From "Town" Group by …..
Practice 4: List number of towns in each city(country) Select countryname, count(…………) From "Town" Group by ….. List ratio of male to total population of each city Select city, 1.0*sum(…..)/sum(….) From "Population" Group by city

96 SQL Joins: connect two or more Tables
A JOIN clause is used to combine rows from two or more tables, based on a related column between them. Populations town population's tid = town's gid

97 SQL Join statement (I) Case 3: Retrieve data from two or more connected Table Select [field_A, field_B, field_C…, *] From table1 join table2 on table1.fieldA = table2.fieldB town Populations From "Population" join "Town" On "Population".tid = "Town".gid tid city town gid countyname townname

98 List all fieldvalues of connected "Population" and "Town" Table
Example: List all fieldvalues of connected "Population" and "Town" Table Select * From "Population" join "Town" On "Population".tid = "Town".gid Example: List population and geometric information of of top 40 biggest towns ( in terms of population ) select countyname, townname, population, geom from "town" join "Population" on "town".gid = "Population".tid Order by "Population".population DESC Limit 40

99 Display SQL results in Q-GIS
For showing SQL result in Q-GIS, we need to transform SQL command into a "View". In SQL, a view is a virtual table based on the result- set of an SQL statement. You can add SELECT, WHERE, and JOIN statements to a view and present the data as if the data were coming from one single table.

100 Create a View [Townpopulation_top40]
It is very easy to create a view from a SQL command. Syntax: CREATE or REPLACE VIEW "name" AS query Example: CREATE or or REPLACE VIEW "Townpopulation_top40" As select countyname, townname, population, geom from "town" join "Population" on "town".gid = "Population".tid Order by "Population".population DESC Limit 40

101 Using Browser Panel Refresh TownPopulationTop40 Right Click Add Layer

102 TownPopulation view Now to create a new view "TownPoulation" for getting the population and boundary of all 368 towns in Taiwan. Please visualize the "TownPopulation" view in QGIS Create or REPLACE View "TownPopulation" as select gid, countyname, townname, male, female, population, geom from "Town" join "Population" on "Town".gid = "Population".tid

103 Showing Statistical information in QGIS with "Graduated Style"
In "TownPoulation", we have the population of all 368 towns in Taiwan. We can use "Graduated Style" function to fill the color of towns according to their populations. Right Click Properties

104 Style Graduated 123 population
Use population field to decide the fill-in color YlOrRd Or Any color you like Equal Interval Separate the range of the possible value of "population" in to 5 "equal interval" classes 5 Classify OK

105 Different Mode of Separating Values
Please Try with different Modes and different number of classes. Quantile (Equal Count) : Classes will have same number of members Natural Breaks: Jenks natural breaks classification method, this method seeks to reduce the variance within classes and maximize the variance between classes. Standard Deviation: it calculates the difference between the filed value of the record in question and the mean value divided by standard deviation of the field value. ("field_name" - mean_value) / standard_daviation

106 Adding Diagram to visualize field values
use "Graduated Style", we can categorize SQL results in to different classes, and fill with different colors. With "Diagram" function, we can have addition pie-charts or histograms for visualizing field values. It is especially useful for comparing different values of the same record.

107 PieChart Size male female Diagrams Next Slider

108 Size 123 population Find 10 5 The size of this chart will be proportional to the value of field "population" Maximal Size will be 10 Minimal Size will be 5

109 Please Try with Histogram

110 Geometry and Spatial Relations
Part5. Geometry and Spatial Relations

111 PostGIS Geography Type
PostGIS supports following Geography data types: Simple Geometry POINT LINESTRING POLYGON Collections: MULTIPOINT: a collection of points MULTILINESTRING: a collection of linestrings MULTIPOLYGON: a collection of polygons GEOMETRYCOLLECTION: a heterogeneous collection of any geometry (including other collections)

112 Check general information about Geography data types
The following threes functions can be used to retrieve some basic background information of a Geography data field: ST_GeometryType(geometry) returns the type of the geometry ST_NDims(geometry) returns the number of dimensions of the geometry ST_SRID(geometry) returns the spatial reference identifier number of the geometry

113 SQL for retrieving basic geographic information
ST_GeometryType(geometry) returns the type of the geometry ST_NDims(geometry) returns the number of dimensions of the geometry ST_SRID(geometry) returns the spatial reference identifier number of the geometry Example: List geographic information for "geom" field in town table Select ST_GeometryType(geom), ST_NDims(geom), ST_SRID(geom) From "Town" Please try with MRTStations, MRTLines, Temples

114 Functions for Point Functions only for Point data type:
ST_X(geometry) returns the X ordinate ST_Y(geometry) returns the Y ordinate ST_AsText(geometry) Returns the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata.

115 SQL for retrieving basic geographic information of Point/MultiPoint type
ST_X(geometry) returns the X ordinate ST_Y(geometry) returns the Y ordinate ST_AsText(geometry): Returns the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata. Example: List geographic information for "geom" field in MRTStations table Select ST_X(geom), ST_Y(geom), ST_AsText(geom) From "Temples" Please try with MRTStations

116 Functions for LineString
Functions only for LineString : ST_Length(geometry) returns the length of the linestring ST_StartPoint(geometry) returns the first coordinate as a point ST_EndPoint(geometry) returns the last coordinate as a point ST_NPoints(geometry) returns the number of coordinates in the linestring

117 SQL for retrieving basic geographic information of LineString type
ST_Length(geometry) returns the length of the linestring ST_StartPoint(geometry) returns the first coordinate as a point ST_EndPoint(geometry) returns the last coordinate as a point ST_NPoints(geometry) returns the number of coordinates in the linestring Example: List geographic information for "geom" field in MRTLines table Select ST_Length(geom), ST_NPoints(geom), ST_StartPoint(ST_GeometryN(geom, 1)), ST_EndPoint(ST_GeometryN(geom, 1)) From "MRTLines" ST_GeometryN(geom, 1) : Get the 1st geometry object from a collection

118 More About ST_Length The SRID of MRTLines Table is : 4326 (WGS84)
The default unit of measuring length of geometry object with SRID 4236 is "degree" In order to get result in "meters", we need to transform the object back to general geography type: Select ST_Length(ST_Transform(geom,4326)::geography) From "MRTLines" ST_Transform(geom,4326)::geography : transform geom field from SRID:4326 to geography type

119 Select ………(ST_Length(ST_Transform(geom,4326)::geography))
Practice 5: “How long is MRT 板南線" Select ………(ST_Length(ST_Transform(geom,4326)::geography)) From "MRTLines" Where …… = '板南線' "List the name and total length of each MRT Lines" Select mrtcode, ………(ST_Length(ST_Transform(geom,4326)::geography)) From "MRTLines" Group by ……..

120 Functions for Polygon Functions only for Point/MultiPoint data type:
ST_Area(geometry) returns the area of the polygons ST_NRings(geometry) returns the number of rings (usually 1, more of there are holes or islands) Select townname, ST_Area(ST_Transform(geom,4326)::geography) as area, ST_Nrings(geom) From "Town" Order by area DESC

121 From town join population on town.gid=population.tid
Practice 6: “List total area (in km2 ) of all counties in Taiwan" Select …, …..(ST_Area(ST_Transform(geom,4326)::geography)) From "Town" Group by …. "List the Population density (persons/ km2)of all towns in 新北市" Select …, …..../ From town join population on town.gid=population.tid

122 Your Exercises Please try to fill colors to the 10 biggest town in Taiwan( in terms of area).

123 Use of Spatial Relationships
Spatial databases have the ability to compare relationships between geometries. Questions like “Which are the closest MRT Staions to a temple?” or “How many people are live in the towns which has a least one MRT line going through." This can only be answered by comparing geometries representing the MRT stations , MRT lines, and towns.

124 ST_Intersects ST_Intersects(geometry A, geometry B) returns t (TRUE) if the two shapes have any space in common, i.e., if their boundaries or interiors intersect.

125 ST_Intersects Examples
Example: List towns which intersects with "金山區" (1) The geometry object of "金山區" select geom from "Town" where countyname='新北市' and townname='金山區' (2) Select records from Town table, where record's geom has intersects with geometry object of "金山區" Select townname, geom From "Town" Where ST_Intersects(geom, **) //** is geometry object of "金山區" (3) Combine those two Quries. See. next page

126 Try to visualize them in QGIS
select geom from "Town" where countyname='新北市' and townname='金山區' + Select countyname, townname, geom From "Town" Where ST_Intersects(geom, **) //** is geometry object of "金山區" = Select countyname, townname, geom From "Town" Where ST_Intersects(geom, (select geom from "Town" where countyname='新 北市' and townname='金山區' ) ) Try to visualize them in QGIS

127 ST_Crosses ST_Crosses(geometry A, geometry B) returns TRUE if their intersection "spatially cross", that is, the geometries have some, but not all interior points in common. The intersection of the interiors of must have a dimensionality less than the maximum dimension of the two input geometries.

128 ST_Cross Examples Select * From "MRTLines" Where ST_Crosses(geom, (
Example: List MRT Lines which crosses "新北市 板橋區" (1) The geometry object of "新北市 板橋區" select geom from "Town" where countyname='新北市' and townname='板橋區' (2) Select records from MRTLines table, where record's geom cross with geometry object of "金山區" Select * From "MRTLines" Where ST_Crosses(geom, ( select geom from "Town" where countyname='新北市' and townname='板橋區' ) ) One limitation, the above query works only if the subquery returns exactly one record !! So, this method cannot answer the question from other prospect: List all Towns which is crossed by MRT Lines "板南線"

129 ST_Cross Examples II Select countyname, townname, "Town".geom
Example: List all Towns which is crossed by MRT Lines "板南線" We perform spatial join to solve the problem Select countyname, townname, "Town".geom From "Town" join "MRTLines" on ST_Crosses("Town".geom, "MRTLines".geom) where mrtcode='板南線'

130 Practice : List MRT Lines which crosses the Town where more than person lives Select "MRTLines".gid,mrtcode, "MRTLines".geom, "Town".townname From "Town" join "MRTLines" on ST_Crosses("Town".geom, "MRTLines".geom) join "Population" on "Town".gid="Population".tid where Population > order by "Town".townname

131 ST_Within and ST_Contains
ST_Within and ST_Contains test whether one geometry is fully within the other.

132 Example: List all Temples in "金山區" and "萬里區"
Select "Temples".id,"Temples".name, "Town".gid,"Town".townname From "Temples" join "Town" on ST_Within("Temples".geom, "Town".geom) where "Town".townname='金山區' or "Town".townname = '萬里區' Practice: List the number of Temples in every town in '台中市'

133 ST_Distance and ST_DWithin
An extremely common GIS question is “find all the stuff within distance X of this other stuff”. The ST_Distance(geometry A, geometry B) calculates the shortest distance between two geometries and returns it as a float. the ST_DWithin(geometry A, geometry B, distance) function provides an index-accelerated true/false test. This is useful for questions like “how many trees are within a 500 meter buffer of the road?”.

134 Example: List all Temples located within 500 meters of "善導寺站" Select "Temples".id, "Temples".name,"MRTStations".landmarkna, ST_Distance( ST_Transform("Temples".geom,4326)::geography, ST_Transform("MRTStations".geom,4326)::geography ) from "Temples" join "MRTStations" on ST_DWithin( ST_Transform("MRTStations".geom,4326)::geography, 500) where "MRTStations".landmarkna='捷運善導寺站'

135 Practice: what is the nearest MRTStations (or exist) to the temple "金龍禪寺(d114A20)" Hint: 1. use last example as template 2. if you want to join two tables without any field in common, use "cross join" instead of "join"


Download ppt "Topic 1. Using PostGis To Manage Your GIS Data"

Similar presentations


Ads by Google