Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Functions returning geometries
4. ST_PointOnSurface
Collections
Summary

Instruction

Good job!. As you saw in the previous example, ST_Centroid can return a point that lies outside a given linestring (or a polygon, too). More specifically, this happens when you work with convex geometries.

Comparison

If you wish to have a central point that is guaranteed to lie inside your geometry, you need to use the ST_PointOnSurface function, like so:

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

There are two drawbacks to using ST_PointOnSurface. First, under the hood, it is much more complex to compute than ST_Centroid, so you should only use it when you really need it. Second, the point returned by ST_PointOnSurface is not guaranteed to be at the exact center of the polygon. In fact, the PostGIS documentation doesn't explain how it is calculated at all. The center that this function returns is merely a point that lies somewhere near the geometric center of the polygon, but always inside it.

Exercise

Once again, show the id, course (in the internal PostGIS format), and central point for the San Francisco railway with the id of 86. This time, though, the central point should lie on the railway.

Take a look at the map again. As you can see, the center point now lies on the railway.

Stuck? Here's a hint!

Invoke ST_PointOnSurface on the course column of the sf_selected_railways table.