How the CENTROID() function works in Mariadb?
The CENTROID()
function is a spatial function that returns the geometric center of a geometry value. The centroid of a geometry is the point that balances the geometry if it is placed on a plane.
The MariaDB CENTROID()
function is used to calculate the geometric center of a spatial feature, which is the average position of all the points in all the coordinate dimensions of the feature. It is commonly used in geographic information systems (GIS) for spatial analysis.
Syntax
The syntax for the MariaDB CENTROID()
function is as follows:
CENTROID(g)
Where g
is a geometry from which the centroid is calculated. The function returns a point that represents the centroid of the geometry.
Examples
Example 1: Centroid of a Polygon
To find the centroid of a simple polygon:
SELECT AsText(CENTROID(Polygon(LineString(Point(0, 0), Point(4, 0), Point(4, 4), Point(0, 4), Point(0, 0)))));
POINT(2 2)
The output is POINT(2 2)
which is the centroid of the square polygon.
Example 2: Centroid of a LineString
This example shows the centroid of a LineString
:
SELECT AsText(CENTROID(LineString(Point(0, 0), Point(4, 4))));
POINT(2 2)
The output is POINT(2 2)
which is the centroid of the line.
Example 3: Using CENTROID()
with a Table
To use CENTROID()
with table data, let’s create a table with spatial data:
DROP TABLE IF EXISTS shapes;
CREATE TABLE shapes (g GEOMETRY);
INSERT INTO shapes VALUES (Polygon(LineString(Point(0, 0), Point(4, 0), Point(4, 4), Point(0, 4), Point(0, 0))));
Now, let’s find the centroid:
SELECT AsText(CENTROID(g)) FROM shapes;
POINT(2 2)
The output is POINT(2 2)
which is the centroid of the polygon stored in the table.
Example 4: Centroid of a Complex Geometry
Let’s find the centroid of a complex geometry:
SELECT AsText(CENTROID(GeomFromText('MULTIPOLYGON(((0 0, 4 0, 4 4, 0 4, 0 0)),((5 5, 9 5, 9 9, 5 9, 5 5)))')));
POINT(4.5 4.5)
The output is POINT(4.5 4.5)
which is the centroid of the multipolygon.
Related Functions
- The
ENVELOPE()
function is used to return the minimum bounding rectangle of a geometry. - The
GEOMETRYN()
function is used to return the N-th geometry from aGeometryCollection
. - The
AREA()
function is used to return the area of a polygon.
Conclusion
The CENTROID()
function in MariaDB is a powerful tool for spatial analysis, providing a simple way to find the center of various geometric shapes. This function is particularly useful in fields such as urban planning, environmental science, and geography, where understanding the spatial characteristics of features is crucial. By leveraging the CENTROID()
function, analysts can gain insights into the distribution and balance of spatial data.