Use of PostgreSQL+PostGIS

PostgreSQL is the world's most technologically advanced open source database . Its predecessor was a non-relational database named Ingres from Berkeley in 1977. Its project leader is Professor Michael Stonebraker. The professor commercialized Ingres in 1982; in 1985, Professor Michael Stonebraker returned to Berkeley to begin research on new database designs, and the following year at the U.S. Defense Advanced Research Projects Agency (DARPA), Army Research Office (ARO), The Postgres (Post-Ingres) project was launched under the auspices of the National Science Foundation (NSF) and ESL, Inc.

Postgres formed the first Demo in 1987, released the first version in 1989, until version 4.2 in 1993. Due to too many external users, the time to do technical support and maintain the source code affected the research on the database, so Berkeley stopped the project. During this time, the Postgres project has been used in some GIS systems.

The Postgres project did not die. In 1994, two Berkeley graduate students added a SQL language interpreter to Postgres, renamed it Postgre95 and published it on the Internet. After some hacking modifications, Postgres95 was renamed PostgreSQL again in 1996, and the first open source version was released under the BSD license. After years of development, PostgreSQL has developed into a very advanced open source database, and its support features and performance are comparable to many advanced commercial databases.

Here is a comparison of the characteristics of mainstream databases in the world, and those who are interested can get a glimpse of PostgreSQL's achievements in the database field.
http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems

PostGIS is an extension of PostgreSQL, the purpose is to enable PostgreSQL to support the storage and use of spatial data, and its essence is similar to ArcSDE and Oracle Spatial Extension. PostGIS is released under the GPL license, fully implements OGC's "Simple Features Specification for SQL" specification, and was certified by OGC in 2006. On this basis, PostGIS has also extended some specifications, which we can learn about in the following features.

 2. Geometry types in

PostGIS PostGIS supports all the "Simple Features" types of the OGC specification, and extends the support for 3DZ, 3DM, and 4D coordinates on this basis.

1. OGC's WKB and WKT formats

OGC defines two formats for describing geometric objects, namely WKB (Well-Known Binary) and WKT (Well-Known Text).

In the SQL statement, you can use the WKT format to define geometric objects in the following ways:
POINT(0 0) - point
LINESTRING(0 0,1 1,1 2) - line
POLYGON((0 0,4 0,4 ​​4 ,0 4,0 0),(1 1, 2 1, 2 2, 1 2,1 1))
——Surface MULTIPOINT(0 0,1 2)
——Multipoint MULTILINESTRING((0 0,1 1,1 2),(2 3,3 2,5 4)) ——Multi-line
MULTIPOLYGON(((0 0,4 0,4 ​​4,0 4,0 0),(1 1,2 1,2 2,1 2 ,1 1)), ((-1 -1,-1 -2,-2 -2,-2 -1,-1 -1)))
——Multifaceted GEOMETRYCOLLECTION(POINT(2 3),LINESTRING((2 3,3 4))) ——Geometry collection

The following statement can use the WKT format to insert a point feature into a table, and the functions such as GeomFromText used in it will be described in detail later:
INSERT INTO table ( SHAPE, NAME )
VALUES ( GeomFromText('POINT(116.39 39.9)', 4326), 'Beijing');

2. EWKT, EWKB and Canonical formats

EWKT and EWKB have 3DZ, 3DM, 4D coordinates and internal extensions compared to OGC WKT and WKB formats. Embedded spatial reference support.

The following defines some geometric objects in EWKT statements:
POINT(0 0 0) - 3D point
SRID=32632; POINT(0 0) - point with embedded spatial reference
POINTM(0 0 0) - point with M value
POINT(0 0 0 0) - 3D point with M value
SRID=4326; MULTIPOINTM(0 0 0,1 2 1) - Multipoint with M value with embedded spatial reference The

following statement can use EWKT format to insert a Point features to a table:
INSERT INTO table ( SHAPE, NAME )
VALUES ( GeomFromEWKT('SRID=4326;POINTM(116.39 39.9 10)'), 'Beijing' )

Canonical format is a hexadecimal-coded geometric object, which can be used directly This is the format that is queried by the SQL statement.

3. SQL-MM format

SQL-MM format defines some interpolation curves. These interpolation curves are somewhat similar to EWKT. They also support 3DZ, 3DM, and 4D coordinates, but do not support embedded spatial references.

The following defines some interpolated geometric objects in SQL-MM statements:
CIRCULARSTRING(0 0, 1 1, 1 0) - Interpolated arc
COMPOUNDCURVE(CIRCULARSTRING(0 0, 1 1, 1 0),(1 0, 0 1)) - Interpolated compound curve
CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),(1 1 , 3 3, 3 1, 1 1)) ——Curve Polygon
MULTICURVE((0 0, 5 5),CIRCULARSTRING(4 0, 4 4, 8 4)) ——Multicurve

MULTISURFACE(CURVEPOLYGON(CIRCULARSTRING(0 0, 4 0, 4 4, 0 4, 0 0),(1 1, 3 3, 3 1, 1 1)),((10 10, 14 12, 11 10, 10 10 ),(11 11, 11.5 11, 11 11.5, 11 11))) - Polysurface

3. Realization of Spatial Information Processing in PostGIS

1. spatial_ref_sys table

In the public mode of the database created based on PostGIS template, there is a spatial_ref_sys table, which stores the spatial reference of the OGC specification. Let's take a look at the 4326 reference we are most familiar with: its srid stores the Well-Known ID of the spatial reference. The definition of this spatial reference mainly includes two fields. srtext stores the spatial reference described by a string, proj4text It stores the PROJ.4 projection definition described as a string (PostGIS uses PROJ.4 to implement projection). srtext content of 4326 spatial reference: GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0 ,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328, AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"











The geometry_columns table stores the information of all geometry fields in the current database. For example, there are two spatial tables in my current library. In the geometry_columns table, the definitions of the geometry fields in the two spatial tables can be found: The f_table_schema field represents the space The schema where the table is located, the f_table_name field represents the table name of the spatial table, the f_geometry_column field represents the name of the geometry field in the spatial table, and the srid field represents the spatial reference of the spatial table. 3. Create a spatial table in PostGIS Creating a spatial table with a geometry field in PostGIS is divided into 2 steps: the first step is to create a general table, and the second step is to add a geometry field to this table. The following first creates a general table named cities in test mode: create table test.cities (id int4, name varchar(20)) and then add a geometry field (two-dimensional point) named shape to cities: select AddGeometryColumn( 'test', 'cities', 'shape', 4326, 'POINT', 2) 4. PostGIS checks the geometric information PostGIS can check the correctness of the geometric information, which is mainly achieved through the IsValid function. The following statement checks the correctness of the two geometric objects. Obviously, points (0, 0) and (1, 1) can form a line, but points (0, 0) and (0, 0) cannot form a line. , the result of the execution of this statement is TRUE, FALSE. select IsValid('LINESTRING(0 0, 1 1)'), IsValid('LINESTRING(0 0,



















By default, PostGIS does not use the IsValid function to check new data inserted by the user, because this will consume more CPU resources (especially complex geometric objects). When you need to use this feature, you can use the following statement to create a new constraint for the table:
ALTER TABLE cities
ADD CONSTRAINT geometry_valid
CHECK (IsValid(shape))

When we try to insert a wrong spatial object into this table, will get an error:
INSERT INTO test.cities ( shape, name )
VALUES ( GeomFromText('LINESTRING(0 0,0 0)', 4326), 'Beijing');

ERROR: new row for relation "cities" violates check constraint "geometry_valid"
SQL status: 23514

5. The spatial index

database in PostGIS has two index schemes for accessing multidimensional data, R-Tree and GiST (Generalized Search Tree). GiST in PostgreSQL is more robust than R-Tree Better, so PostGIS's indexing of spatial data is generally implemented using GiST.

The following statement adds a spatial index shape_index_cities to the cities table in the sde schema, and the same function can be done through the graphical interface in pgAdmin.
CREATE INDEX shape_index_cities
ON sde.

(shape);

Another thing to note is that spatial indexes only work with bounded range-based queries, such as the "&&" operation. 

4. Common functions in PostGIS The

following content includes a lot of angle brackets, which will be displayed abnormally when posted to blogger. There is too much content and I have no time to manually change the code one by one, so if you have any questions, please refer to the official PostGIS documentation.

First of all, it needs to be explained that many functions here are named in the form of ST_[X]yyy. In fact, many functions can also be accessed in the form of xyyy. In the PostGIS function library, we can see that the definitions of these two functions are exactly the same.

1. OGC standard function

management functions:
Add geometry field AddGeometryColumn(, , , , , )
Delete geometry field DropGeometryColumn(, , )
Check database geometry field and file in geometry_columns Probe_Geometry_Columns()
Set spatial reference to geometry objects (in a range through a range) Commonly used when doing spatial queries) ST_SetSRID(geometry, integer)

geometric object relationship function :
get the distance between two geometric objects ST_Distance(geometry, geometry)
If the distance between two geometric objects is within the given value range, return TRUE ST_DWithin( geometry, geometry, float) to
determine whether two geometric objects are equal
(for example, LINESTRING(0 0, 2 2) and LINESTRING(0 0, 1 1, 2 2) are the same geometric object) ST_Equals(geometry, geometry) to
determine two Whether the geometry object is separated ST_Disjoint(geometry, geometry)
Determine whether two geometric objects intersect ST_Intersects(geometry, geometry)
Determine whether the edges of two geometric objects touch ST_Touches(geometry, geometry)
Determine whether two geometric objects pass through each other ST_Crosses(geometry, geometry)
Determine whether A is contained by B ST_Within (geometry A, geometry B) to
determine whether two geometric objects overlap ST_Overlaps(geometry, geometry)
to determine whether A contains B ST_Contains(geometry A, geometry B)
to determine whether A covers B ST_Covers(geometry A, geometry B)
to determine whether A Covered by B ST_CoveredBy(geometry A, geometry B)
Determine whether the relationship between two geometric objects is established by DE-9IM matrix ST_Relate(geometry, geometry, intersectionPatternMatrix)
Obtain the relationship between two geometric objects (DE-9IM matrix) ST_Relate(geometry , geometry)

geometric object processing function:
get the center of the geometric object ST_Centroid(geometry)
area measurement ST_Area(geometry)
length measurement ST_Length(geometry)
returns a point on the surface ST_PointOnSurface(geometry)
Get the boundary ST_Boundary(geometry)
Get the buffered geometric object ST_Buffer(geometry, double, [integer])
Get the external object of the multi-geometry object ST_ConvexHull(geometry)
Get the part where the two geometric objects intersect ST_Intersection(geometry, geometry)
The longitude will be less than The value of 0 plus 360 makes all longitude values ​​between 0-360 ST_Shift_Longitude(geometry)
to obtain the disjoint part of two geometric objects (A and B are interchangeable) ST_SymDifference(geometry A, geometry B)
removes the intersection of B and B from A Return ST_Difference(geometry A, geometry B)
returns the merged result of two geometric objects ST_Union(geometry, geometry)
returns the merged result of a series of geometric objects ST_Union(geometry set)
completes the merging with less memory and longer time Operation, the result is the same as ST_Union ST_MemUnion(geometry set)

Geometry object access function:
Get the WKT description of the geometry object ST_AsText(geometry)
Get the WKB description of the geometry object ST_AsBinary(geometry)
Get the spatial reference ID of the geometry object ST_SRID(geometry)
Get the geometry The dimension of the object ST_Dimension(geometry)
gets the bounding range of the geometric object ST_Envelope(geometry)
Determine whether the geometric object is empty ST_IsEmpty(geometry)
Determine whether the geometric object does not contain special points (such as self-intersection) ST_IsSimple(geometry)
Determine whether the geometric object is closed ST_IsClosed(geometry)
Determine whether the curve is closed and does not contain special points ST_IsRing(geometry)
Get The number of objects in the multi-geometry object ST_NumGeometries(geometry)
Get the Nth object in the multi-geometry object ST_GeometryN(geometry, int)
Get the number of points in the geometry object ST_NumPoints(geometry)
Get the Nth point of the geometric object ST_PointN(geometry ,integer)
Get the outer edge of the polygon ST_ExteriorRing(geometry)
Get the number of inner boundaries of the polygon ST_NumInteriorRings(geometry)
Same as above ST_NumInteriorRing(geometry)
Get the Nth inner boundary of the polygon ST_InteriorRingN(geometry, integer)
Get the end point of the line ST_EndPoint(geometry)
Get The starting point of the line ST_StartPoint(geometry)
gets the type of the geometric object GeometryType(geometry)
is similar, but the M value is not checked, that is, the POINTM object will be judged as point ST_GeometryType(geometry)
Get the X coordinate of the point ST_X(geometry)
Get the Y coordinate of the point ST_Y(geometry)
Get the Z coordinate of the point ST_Z(geometry)
Get the M value of the point ST_M(geometry)

Geometry object constructor :
Reference semantics:
Text: WKT
WKB: WKB
Geom:Geometry
M:Multi
Bd:BuildArea
Coll:Collection ST_GeomFromText(text,[])

ST_PointFromText(text,[])
ST_LineFromText(text,[])
ST_LinestringFromText(text,[])
ST_PolyFromText(text,[])
ST_PolygonFromText(text,[])
ST_MPointFromText(text,[ ])
ST_MLineFromText(text,[])
ST_MPolyFromText(text,[])
ST_GeomCollFromText(text,[])
ST_GeomFromWKB(bytea,[])
ST_GeometryFromWKB(bytea,[])
ST_PointFromWKB(bytea,[])
ST_LineFromWKB(bytea,[]) )
ST_LinestringFromWKB(bytea,[])
ST_PolyFromWKB(bytea,[])
ST_PolygonFromWKB(bytea,[])
ST_MPointFromWKB(bytea,[])
ST_MLineFromWKB(bytea,[])
ST_MPolyFromWKB(bytea,[])
ST_GeomCollFromWKB(bytea,[])
ST_BdPolyFromText(text WKT, integer SRID)

ST_BdMPolyFromText(text WKT, integer SRID)

 2. PostGIS extension function

management functions:

delete a spatial table (including records in geometry_columns) DropGeometryTable([], )
Update the spatial reference of the spatial table UpdateGeometrySRID([], , , )
Update the statistics of the spatial table update_geometry_stats([, ] ) reference

semantics : Geos :
GEOS library
Jts : JTS library
Proj :

PROJ4 library Operator: A range = B range A = B A range covers B range or A range is left of B range A &<> B A range is left of B range A <<>> B















A range covers B range or A range is below B range A &<| BA range covers B range or A range is above B range A |&> B
A range is below B range A <<| BA range is above B range A |>> B
A=BA ~= B
A range is contained by B range A @ B
A range contains B range A ~ B
A range covers B range A && B

Geometric measurement function:

measure area ST_Area(geometry)
according to latitude and longitude points Calculate the distance on the surface of the earth, in meters, the radius of the earth is 6370986 meters ST_distance_sphere(point, point)
Similarly, use the specified earth ellipsoid parameters ST_distance_spheroid(point, point, spheroid)
to measure the length of the 2D object ST_length2d(geometry)
Measure the length of a 3D object ST_length3d(geometry)
Calculate the length on the surface of the earth based on the latitude and longitude object ST_length_spheroid(geometry, spheroid)
ST_length3d_spheroid(geometry, spheroid)
Measure the distance between two objects ST_distance(geometry, geometry)
Measure the distance between two lines The maximum distance between ST_max_distance(linestring,linestring)
measures the perimeter of the 2D object ST_perimeter(geometry)
ST_perimeter2d(geometry)
Measure the perimeter of a 3D object ST_perimeter3d(geometry)
Measure the azimuth angle formed by two points, in radians ST_azimuth(geometry, geometry)

Geometry output:
Reference semantics:
NDR: Little Endian
XDR: big-endian
HEXEWKB: Canonical
SVG: SVG Format
GML: GML Format
KML: KML Format
GeoJson: GeoJson Format

ST_AsBinary(geometry,{'NDR'|'XDR'})
ST_AsEWKT(geometry)
ST_AsEWKB(geometry, {'NDR'|'XDR'})
ST_AsHEXEWKB(geometry, { 'NDR'|'XDR'})
ST_AsSVG(geometry, [rel], [precision])
ST_AsGML([version], geometry, [precision])
ST_AsKML([version], geometry, [precision])
ST_AsGeoJson([version] , geometry, [precision], [options])

geometry object creation:

reference semantics:
Dump: dump ST_GeomFromEWKT(text)

ST_GeomFromEWKB(bytea)
ST_MakePoint(, , [], [])
ST_MakePointM(, , )
ST_MakeBox2D(, )
ST_MakeBox3D(, )
ST_MakeLine(geometry set)
ST_MakeLine(geometry, geometry)
ST_LineFromMultiPoint(multipoint)
ST_MakePolygon(linestring, [linestring[] ])
ST_BuildArea(geometry)
ST_Polygonize(geometry set)
ST_Collect(geometry set)
ST_Collect(geometry, geometry)
ST_Dump(geometry)
ST_DumpRings(geometry)

Geometry Editing:

Adding a boundary to a geometry makes the query faster ST_AddBBOX(geometry)
Delete the boundary of the geometry object ST_DropBBOX(geometry)
Add, delete, set point ST_AddPoint(linestring, point, [])
ST_RemovePoint(linestring, offset)
ST_SetPoint(linestring, N, point)
Geometry object type conversion ST_Force_collection(geometry)
ST_Force_2d(geometry)
ST_Force_3dz(geometry), ST_Force_3d(geometry),
ST_Force_3dm(geometry)
ST_Force_4d(geometry)
ST_Multi(geometry)
Convert the geometric object to the specified spatial reference ST_Transform(geometry, integer)
to 3D Affine transformation of geometry objects ST_Affine(geometry, float8, float8, float8, float8, float8, float8, float8, float8, float8, float8, float8, float8)
Affine transformation of 2D geometry objects ST_Affine(geometry, float8, float8, float8, float8, float8, float8)
Offset geometry ST_Translate(geometry, float8, float8, float8)
Scale geometry ST_Scale(geometry, float8, float8, float8)
Rotate 3D geometry ST_RotateZ(geometry, float8 )
ST_RotateX(geometry, float8)
ST_RotateY(geometry, float8)
Offset and scale 2D objects ST_TransScale(geometry, float8, float8, float8, float8)
Invert ST_Reverse(geometry)
Convert to right hand rule ST_ForceRHR(geometry)
Refer to IsSimple function
Use Douglas-Peuker algorithm ST_Simplify(geometry, tolerance)
ST_SimplifyPreserveTopology (geometry, tolerance)
The vertices of the geometric object are snapped to the grid ST_SnapToGrid(geometry, originX, originY, sizeX, sizeY)
ST_SnapToGrid(geometry, sizeX, sizeY), ST_SnapToGrid(geometry, size)
The second parameter is a point, specifying the origin coordinates ST_SnapToGrid(geometry, geometry, sizeX, sizeY, sizeZ, sizeM)
segment ST_Segmentize(geometry, maxlength)
merge into line ST_LineMerge(geometry)

Linear reference:

get the point of the location according to location (0-1) ST_line_interpolate_point(linestring, location)
Get a line ST_line_substring(linestring, start, end)
Obtain location according to point (0-1) ST_line_locate_point(LineString, Point)
Obtain geometric object according to measurement value ST_locate_along_measure(geometry, float8)
Obtain geometric object collection according to measurement value interval ST_locate_between_measures(geometry, float8, float8)

Miscellaneous function function:
geometry Object summary ST_Summary(geometry)
Boundary of geometry object ST_box2d(geometry)
ST_box3d(geometry)
Boundary of multiple geometry objects ST_extent(geometry set)
0=2d, 1=3dm, 2=3dz, 3=4d ST_zmflag(geometry)
Whether Contains
the dimensions of the Bounding Box ST_HasBBOX(geometry) geometric object: 2, 3, 4 ST_ndims(geometry)
The number of sub-objects ST_nrings(geometry)
ST_npoints(geometry) Whether the
object is successfully verified ST_isvalid(geometry)
Expand the geometric object ST_expand(geometry, float)
Calculate the boundary range of a spatial table ST_estimated_extent([schema], table, geocolumn)
Get the spatial reference ST_find_srid(, , )
The memory size used by the geometry object, in bytes ST_mem_size(geometry)
Whether the point is on the circle ST_point_inside_circle(,,,)
Get the X, Y, Z of the boundary ST_XMin(box3d)
ST_YMin(box3d)
ST_ZMin(box3d)
ST_XMax(box3d)
ST_YMax( box3d)
ST_ZMax(box3d)
Constructs an array of geometry objects ST_Accum(geometry set)

Long transaction support:
enable/disable long transaction support, repeated calls have no side effects EnableLongTransactions()
DisableLongTransactions()
Check if update and delete operations on rows are authorized CheckAuth ([],

, )
lock row LockRow([],

, , , [])
Unlock Rows UnlockRows()
Add Authorization ID to the current transaction AddAuth()

Other SQL-MM and ArcSDE-style functions are supported, please refer to http://postgis.refractions .NET /documentation/manual- 1.3/ch06.html#id2750611

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326491830&siteId=291194637