Introduction
Functions returning geometries
3. ST_Centroid
Collections
Summary

Instruction

When working with PostGIS, we sometimes want to calculate the "center" point of a given geometry. We may want to find the midpoint of a cycling route or the central point of a district, for example. PostGIS offers two functions for this purpose: ST_Centroid and ST_PointOnSurface.

ST_Centroid returns the geometric center (centroid) of a geometry. You can think of it in the following way: if you put a cutout of your geometry on the tip of a pin in the geometric center, the cutout would be perfectly balanced. ST_Centroid is very quick, so it should be your first choice in most cases. Take a look at how it's used:

SELECT
  id,
  name,
  ST_Centroid(boundaries)
FROM sf_hotels;

The query above will find the centroid of each hotel in San Francisco. By default, ST_Centroid returns a geometry in the internal PostGIS format so you can easily store it in the database. If you need a human-readable format, recall that you can always use ST_AsText, like so:

SELECT
  id,
  name,
  ST_AsText(
    ST_Centroid(boundaries))
FROM sf_hotels;

Exercise

Now it's your turn. Display the id, course (in the internal PostGIS format), and centroid (in the internal PostGIS format) of the San Francisco railway with the id of 86. The tabular result doesn't say much, but if you take a look at the map and zoom in, you'll notice that the centroid lies outside the path of the railway as opposed to on the railway.

Stuck? Here's a hint!

Use the ST_Centroid function on the course column of thesf_selected_railways table.

Console

Code editor

Result

TableConsoleMap