Create a Spatial Table and Insert Data
Now that you have a spatial database, you can create tables to store geographic data. In this step, you will create a cities table and insert the coordinates for a few major cities.
You should still be in the psql shell, connected to the spatial_db database.
First, create a table named cities. This table will have a standard id and name, along with a location column of type GEOMETRY.
Understanding GEOMETRY(Point, 4326)
GEOMETRY: This is the fundamental PostGIS data type for storing spatial features.
Point: This specifies that the geometry column will only store points. Other types include LINESTRING and POLYGON.
4326: This is the Spatial Reference System Identifier (SRID). SRID 4326 corresponds to WGS 84, the standard coordinate system used by GPS and Google Maps.
Execute the following command to create the table:
CREATE TABLE cities (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
location GEOMETRY(Point, 4326)
);
You will see the confirmation:
CREATE TABLE
Next, insert data into the cities table. You will use the ST_GeomFromText function to convert Well-Known Text (WKT) representations of points into geometry objects. The format is POINT(longitude latitude).
INSERT INTO cities (name, location) VALUES
('New York', ST_GeomFromText('POINT(-74.0060 40.7128)', 4326)),
('London', ST_GeomFromText('POINT(-0.1278 51.5074)', 4326)),
('Tokyo', ST_GeomFromText('POINT(139.6917 35.6895)', 4326));
The output indicates that three rows were inserted:
INSERT 0 3
To verify that the data was inserted correctly, you can query the table. Use the ST_AsText function to convert the geometry object back into a human-readable text format.
SELECT id, name, ST_AsText(location) FROM cities;
The output should display the data you just inserted:
id | name | st_astext
----+----------+-----------------------------
1 | New York | POINT(-74.006 40.7128)
2 | London | POINT(-0.1278 51.5074)
3 | Tokyo | POINT(139.6917 35.6895)
(3 rows)
You have successfully created a spatial table and populated it with data.