Introduction to basic common functions in PostGIS spatial data

Table of contents

foreword

1. Basic data

1. Data structure preparation

2. Basic data structure

2. Commonly used spatial functions

1. st_srid Get the spatial object SRID

 2. st_asgeojson geojson conversion

3. st_aswkt wkt support

4. st_area area calculation

5. ST_Buffer buffer

 6. Other functions

Summarize


foreword

        In recent years, GIS-oriented applications have sprung up like mushrooms, and its underlying spatio-temporal database plays a pivotal role in the process of geographic information and spatio-temporal data management system construction. Spatial information is stored in spatial databases, which have their own uniqueness in data management compared with traditional relational databases, such as spatial indexes that are different from traditional indexes.

        As we all know, a function is a set of functional methods in a database that specifically deal with a problem, such as time functions, numeric functions, and string functions in a relational database. In a spatial database, it not only includes all functions in these relational databases, but also integrates More abundant spatial functions, especially the most standard and abundant realized by PostGIS spatial library.

        This article will focus on the PostGIS spatial database, focusing on several commonly used spatial functions in spatial databases, and guide readers to understand the basic use of functions through examples.

1. Basic data

1. Data structure preparation

        Before performing spatial data query, first define the data structure. In addition to the common relational database structure definition, spatial fields must be included in the spatial database field design. The detailed database structure refers to the following design:

-- ----------------------------
-- Table structure for dltb4326
-- ----------------------------
DROP TABLE IF EXISTS "dltb4326";
CREATE TABLE "dltb4326" (
  "gid" int4 NOT NULL DEFAULT nextval('dltb4326_gid_seq'::regclass),
  "objectid" int4,
  "qsxz" varchar(2),
  "qsdwdm" varchar(19),
  "qsdwmc" varchar(60),
  "zldwdm" varchar(19),
  "zldwmc" varchar(60),
  "tbmj" numeric,
  "kcdlbm" varchar(5),
  "kcxs" numeric,
  "kcmj" numeric,
  "tbdlmj" numeric,
  "gdlx" varchar(2),
  "gdpdjb" varchar(2),
  "gddb" int4,
  "frdbs" varchar(1),
  "czcsxm" varchar(4),
  "sjnf" int4,
  "mssm" varchar(2),
  "hdmc" varchar(100),
  "bz" varchar(254),
  "shape_leng" numeric,
  "shape_area" numeric,
  "geom" "geometry"
)
;

-- ----------------------------
-- Indexes structure for table dltb4326
-- ----------------------------
CREATE INDEX "dltb4326_geom_idx" ON "dltb4326" USING gist (
  "geom" "public"."gist_geometry_ops_2d"
);

-- ----------------------------
-- Primary Key structure for table dltb4326
-- ----------------------------
ALTER TABLE "dltb4326" ADD CONSTRAINT "dltb4326_pkey" PRIMARY KEY ("gid");

2. Basic data structure

        After designing the database table structure, data initialization is required. How to initialize data in the database will not be explained here. The data is shown as follows:

        You can display the spatial fields in pgAdmin. There is a preview button in the last spatial field queried. Click the left mouse button to complete the data preview. The effect is as follows:

2. Commonly used spatial functions

1. st_srid Get the spatial object SRID

        In the spatial database, you can use the st_srid() function to view the srid information of the spatial data. You can see its specific function definition in postgis:

CREATE OR REPLACE FUNCTION "public"."st_srid"("geom" "public"."geometry")
  RETURNS "pg_catalog"."int4" AS '$libdir/postgis-3', 'LWGEOM_get_srid'
  LANGUAGE c IMMUTABLE STRICT
  COST 1

        When calling the function, you only need to pass in the spatial data. It is worth noting that st_srid not only supports geometry, but also supports geography. You can find relevant information about the difference between geography and geometry.

select st_srid(geom) from dltb4326 limit 1;

        The result after running the function is as follows:

 2. st_asgeojson geojson conversion

In a spatial database, in order to maintain storage efficiency, data is usually stored in binary format, such as the following format:

         Although the above formats are the most efficient for data storage, they are less readable for users. geojson is a json data format for geographic data formats, which has the advantage of high readability. In postGIS, data conversion is performed through st_asgeojson.

CREATE OR REPLACE FUNCTION "public"."st_asgeojson"(text)
  RETURNS "pg_catalog"."text" AS $BODY$ SELECT public.ST_AsGeoJson($1::public.geometry, 9, 0);  $BODY$
  LANGUAGE sql IMMUTABLE STRICT
  COST 500
select st_asgeojson(geom) from dltb4326;

 One of the geojson data is as follows:

{"type":"MultiPolygon","coordinates":[[[[112.948902049,28.031646521],[112.948934463,28.031602495],[112.948947087,28.03160557],[112.948990862,28.031516143],[112.948970512,28.031507049],[112.948915856,28.031482624],[112.948953672,28.031411773],[112.948989778,28.031426021],[112.949058815,28.031135666],[112.948993581,28.031122934],[112.948972683,28.031147219],[112.948939525,28.031192802],[112.948837509,28.031234815],[112.948830726,28.031238787],[112.948818769,28.031259925],[112.948799172,28.031296293],[112.948793881,28.031313083],[112.948783858,28.031341866],[112.948778722,28.031356612],[112.948761457,28.031402316],[112.948760048,28.031405735],[112.948759101,28.031427842],[112.948823424,28.031465486],[112.948871536,28.031498082],[112.948876579,28.031532736],[112.948861376,28.031574397],[112.94883146,28.031607591],[112.948813904,28.031614619],[112.94878463,28.03162494],[112.948777458,28.031627469],[112.948740873,28.031654644],[112.948627326,28.031849531],[112.948564719,28.031924253],[112.9485632,28.031942145],[112.948503091,28.032004376],[112.948436182,28.032106517],[112.948384475,28.032166996],[112.94830902,28.032192929],[112.948370033,28.032250988],[112.948396715,28.032267267],[112.94840872,28.032274592],[112.948418868,28.032262969],[112.948557256,28.032104472],[112.948640482,28.032009154],[112.948787309,28.031840991],[112.94880614,28.031819424],[112.948808544,28.031816671],[112.948832592,28.031789129],[112.94885082,28.03173793],[112.948851228,28.031737165],[112.948893567,28.031658044],[112.948902049,28.031646521]]]]}

After getting geojson, many front-end gis frameworks, such as leaflet, cesium, and openlayers, can be displayed directly. 

3. st_aswkt wkt support

        In spatial data, in addition to directly converting spatial data to json, the data format can also be converted to wkt. The support function is st_aswkt

CREATE OR REPLACE FUNCTION "public"."st_asewkt"("public"."geometry", int4)
  RETURNS "pg_catalog"."text" AS '$libdir/postgis-3', 'LWGEOM_asEWKT'
  LANGUAGE c IMMUTABLE STRICT
  COST 500

Query validation on the above spatial table.

select st_asewkt(geom) from dltb4326;

SRID=4326;MULTIPOLYGON(((112.94890204932419 28.03164652145915,112.94893446282308 28.03160249461021,112.94894708668416 28.03160556961373,112.94899086229839 28.03151614262633,112.94897051189844 28.03150704851138,112.94891585590196 28.03148262432319,112.94895367222296 28.0314117725388,112.94898977797723 28.031426021004112,112.94905881545756 28.031135666053835,112.94899358110835 28.031122933916585,112.94897268274052 28.03114721949028,112.94893952469715 28.03119280160087,112.94883750860863 28.031234815284318,112.94883072625771 28.031238786653255,112.94881876908642 28.03125992489088,112.94879917174167 28.0312962928862,112.94879388059157 28.031313082613508,112.94878385840406 28.031341866228075,112.94877872235762 28.031356611674585,112.9487614574029 28.031402316249164,112.94876004837538 28.031405735030464,112.9487591013953 28.03142784174355,112.94882342369294 28.031465486161448,112.94887153560425 28.03149808188427,112.94887657902083 28.031532736410973,112.94886137589438 28.03157439741858,112.9488314598062 28.031607590745498,112.94881390363874 28.03161461870683,112.94878462976982 28.031624939649983,112.94877745771588 28.031627468898503,112.94874087256784 28.031654643500215,112.94862732553705 28.031849531246586,112.94856471938606 28.031924252558934,112.94856320015934 28.031942144854593,112.94850309122222 28.032004375600756,112.9484361819004 28.03210651665418,112.94838447535787 28.032166996273293,112.94830902032196 28.032192928521404,112.94837003282403 28.03225098804355,112.94839671459228 28.03226726728849,112.94840871962174 28.032274591850808,112.94841886802325 28.032262968778635,112.94855725634616 28.032104472143654,112.94864048184257 28.032009153963696,112.94878730879185 28.03184099148005,112.94880613958024 28.031819424476836,112.94880854374979 28.031816671071233,112.94883259161806 28.03178912893942,112.94885081958518 28.03173792962929,112.94885122816191 28.031737165367048,112.94889356660211 28.0316580440782,112.94890204932419 28.03164652145915)))

4. st_area area calculation

        For surface type data in spatial data, in many cases, it is necessary to query the spatial area. In postgis, the st_area function can be used for area calculation.

CREATE OR REPLACE FUNCTION "public"."st_area"("public"."geometry")
  RETURNS "pg_catalog"."float8" AS '$libdir/postgis-3', 'ST_Area'
  LANGUAGE c IMMUTABLE STRICT
  COST 50
select st_area(geom::geography),st_area(geom) from dltb4326;

Here is an interesting example. After the above statement is executed, you can see the following results:

 The spatial functions are the same, the difference is that the parameters passed in are different, one is geography, the other is geometry, you can see that the results of the two operations are not the same. Let me talk about the reason first. In postGIS, by default, if the geometry is passed in to solve the area, when the srid is 4326, the result is displayed in degrees. And geography is displayed in units of meters, and everyone can make reasonable selections according to their own needs during work.

5. ST_Buffer buffer

        In many applications, we need to calculate the range of the original data. For example, to build a bus station, we need to cover a comprehensive range of 2 kilometers. We can build a 2-kilometer buffer surface and return it directly to the front end.

CREATE OR REPLACE FUNCTION "public"."st_buffer"("geom" "public"."geometry", "radius" float8, "quadsegs" int4)
  RETURNS "public"."geometry" AS $BODY$ SELECT public.ST_Buffer($1, $2, CAST('quad_segs='||CAST($3 AS text) as text)) $BODY$
  LANGUAGE sql IMMUTABLE STRICT
  COST 10000
select st_asgeojson(st_buffer(geom,2)) from dltb4326;

 6. Other functions

        In addition to the above common functions, postgis also provides a wealth of spatial functions for everyone. Interested friends can go to the official website of postgis to check. Here are some commonly used functions, which can be used in depth in spatial data. It is these feature-rich functions that make spatial analysis more convenient and faster.

Topological relations
ST_3DIntersects — Returns true if two geometries spatially intersect in 3D — only for points, linestrings, polygons, polysurfaces (regions).
ST_Contains — Returns true if and only if no point of B lies outside A and at least one point inside B lies inside A.
ST_ContainsProperly — Returns true if B intersects the interior of A but not the boundary (or exterior). A itself does not contain itself, but contains itself.
ST_Covers — returns true if no points in B lie outside A
ST_CoveredBy — returns true if no points in Geometry/Geography A lie outside Geometry/Geography B ST_Crosses — returns true
if two geometries have some but not all interiors the same point, returns true.
ST_LineCrossingDirection — Returns a number indicating the intersecting behavior of two LineStrings.
ST_Disjoint — Returns true if two geometries are spatially disjoint (they have nothing in common).
ST_Equals — Returns true if two geometries contain the same set of points in space.
ST_Intersects — Returns true if two Geometry/Geography intersect in 2D space (have at least one point in common).
ST_OrderingEquals — Returns true if two geometries represent the same geometry and have points in the same order of orientation.
ST_Overlaps — Returns true if two geometries intersect and have the same dimensions, but are not completely contained within each other.
ST_Relate — Tests whether two geometries have a topological relationship matching a given "Intersection Matrix" pattern, or computes their "Intersection Matrix" ST_RelateMatch —
Tests whether a DE-9IM intersection matrix matches an Intersection Matrix pattern
ST_Touches — If two geometries are at least have a common point, but their interiors are disjoint, returns true.
ST_Within — Returns true if geometry A is completely within geometry B

Distance relation
ST_3DDWithin — Returns true if two 3D geometries are within a given 3D distance
ST_3DDFullyWithin — Returns true if two 3D geometries are completely within a given 3D distance
ST_DFullyWithin — Returns true if two geometries are completely within a given Within distance, returns true
ST_DWithin — Returns true if two geometries are within a given distance
ST_PointInsideCircle — Tests whether a point geometry is within a circle defined by center and radius.

Measure function
ST_Area — Returns the area of ​​a polygonal geometry.
ST_Azimuth — Returns the azimuth from north, in radians, and the angle in radians from the vertical at point A to point B.
ST_Angle — returns the angle between 3 points or 2 vectors (4 points or 2 lines).
ST_ClosestPoint — Returns the closest 2D point on g1 to g2. This is the first point of the shortest line.
ST_3DClosestPoint — Returns the closest 3D point on g1 to g2. This is the first point of the 3D shortest line.
ST_Distance —Returns the distance between two geometric or geographic values.
ST_3DDistance — Returns the 3D Cartesian minimum distance (based on spatial reference) between two geometries in projected units.
ST_DistanceSphere — Returns the minimum distance in meters between two lon/lat geometries using a spherical earth model.
ST_DistanceSpheroid — Returns the minimum distance between two lon/lat geometries using a spherical earth model.
ST_FrechetDistance — Returns the Fréchet distance between two geometries.
ST_HausdorffDistance — Returns the Hausdorff distance between two geometries.
ST_Length — Returns the 2D length of a linear geometry.
ST_Length2D — Returns the 2D length of a linear geometry. Alias ​​of ST_Length
ST_3DLength — Returns the 3D length of a linear geometry.
ST_LengthSpheroid — Returns the 2D or 3D length/perimeter of the lon/lat geometry on a sphere.
ST_LongestLine — Returns the 2D longest line between two geometries.
ST_3DLongestLine — Returns the 3D longest line between two geometries
ST_MaxDistance — Returns the maximum 2D distance between two geometries in projected units.
ST_3DMaxDistance — Returns the 3D Cartesian maximum distance (based on spatial reference) between two geometries in projected units.
ST_MinimumClearance — Returns the minimum clearance of a geometry, a measure of the robustness of the geometry.
ST_MinimumClearanceLine — Returns the two-point LineString that spans the geometric minimum clearance.
ST_Perimeter — Returns the length of a polygon geometry or geographic boundary.
ST_Perimeter2D — Returns the 2D perimeter of a polygonal geometry. Alias ​​for ST_Perimeter.
ST_3DPerimeter — Returns the 3D perimeter of a polygonal geometry.
ST_Project — Returns the projected point a distance and azimuth (azimuth) from the origin.
ST_ShortestLine — Returns the 2D shortest line between two geometries

Geometry Processing
These functions compute the geometry, or resize or shape the geometry
ST_Buffer—returns a geometry that covers all points within a given distance from the geometry.
ST_BuildArea — Creates a polygonal geometry built from the lines of the geometry.
ST_Centroid — Returns the geometric center of the geometry.
ST_ConcaveHull — Computes a concave geometry that may contain all vertices of the input geometry
ST_ConvexHull — Computes the convex hull of a geometry.
ST_DelaunayTriangles — Returns the Delaunay triangulation of geometry vertices.
ST_FilterByM — Removes vertices based on their M value
ST_GeneratePoints — Generates random points contained within a polygon or multipolygon.
ST_GeometricMedian — Returns the geometric median of the MultiPoint.
ST_MaximumInscribedCircle — Computes the largest circle fully contained within a geometry.
ST_MinimumBoundingCircle — Returns the smallest circular polygon containing geometry.
ST_MinimumBoundingRadius — Returns the center point and radius of the smallest circle that encloses the geometry.
ST_OrientedEnvelope — Returns the rectangle with the smallest area enclosing the geometry.
ST_OffsetCurve — Returns an offset line at a given distance and margin from an input line.
ST_PointOnSurface — Returns a point guaranteed to lie on a polygon or geometry.
ST_Polygonize — Computes the set of polygons formed by the lines of a set of geometries.
ST_ReducePrecision — Returns a valid geometry with all points rounded to the provided grid tolerance.
ST_SharedPaths — Returns a collection containing paths shared by two input linestrings/multilinestrings.
ST_Simplify — Returns a simplified version of the geometry using the Douglas-Peucker algorithm.
ST_SimplifyPreserveTopology — Returns a simplified and efficient version of the geometry using the Douglas-Peucker algorithm.
ST_SimplifyVW — returns a simplified version of the geometry using the Visvalingam-Whyatt algorithm
ST_ChaikinSmoothing — returns a smoothed version of the geometry using the Chaikin algorithm
ST_SetEffectiveArea — sets the effective area per vertex using the Visvalingam-Whyatt algorithm.
ST_VoronoiLines — Returns the boundaries of the Voronoi diagram of geometry vertices.
ST_VoronoiPolygons — Returns the cells of the Voronoi diagram of the vertices of the geometry.

Affine Transformation
These functions use an affine transformation to change the position and shape of a geometry.
ST_Affine — Applies a 3D affine transformation to a geometry.
ST_Rotate —Rotates the geometry around the origin.
ST_RotateX — Rotates the geometry around the X axis.
ST_RotateY — Rotates the geometry around the Y axis.
ST_RotateZ — Rotates the geometry around the Z axis.
ST_Scale — Scales the geometry by the given factor.
ST_Translate —Translate geometry by a given offset.
ST_TransScale — Translates and scales geometry by the given offset and factor.

Summarize

        The above is the main content of this article. This article will focus on the PostGIS spatial database, focusing on several commonly used spatial functions in spatial databases, and guide readers to understand the basic use of functions through examples. The writing is hasty, and it is inevitable that there will be mistakes. Welcome to leave a message in the comment area for criticism and correction.

Guess you like

Origin blog.csdn.net/yelangkingwuzuhu/article/details/132621908