ST_GeometricMedian
What is ST_GeometricMedian?
ST_GeometricMedian is a PostGIS function that returns the point that minimises the sum of Euclidean distances to every point in the input MultiPoint. Also called the 1-median or Fermat–Weber point, it is a robust alternative to the centroid that is far less sensitive to outliers.
ST_GeometricMedian(geometry g, float8 tolerance = NULL, int max_iter = 10000, boolean fail_if_not_converged = false) → geometryThe computation is iterative (Weiszfeld's algorithm); tolerance controls the convergence criterion and max_iter caps the number of iterations.
When would you use ST_GeometricMedian?
Use ST_GeometricMedian when you want a central point that represents the "typical" location of a set of observations and is not pulled by outliers. Classic uses include choosing an optimal facility location, summarising a cluster of GPS pings, or finding the distribution centre that minimises total delivery distance.
1SELECT ST_GeometricMedian(ST_Collect(customer_geom)) AS optimal_hub
2FROM customers
3WHERE region_id = 'west';FAQs
How is the geometric median different from the centroid?
The centroid (mean) minimises the sum of squared distances, which heavily weights outliers. The geometric median minimises the sum of distances and is much more robust — if 90% of your points are in one place and 10% are far away, the centroid will drift toward the outliers while the median stays near the main cluster.
Is there always a unique solution?
Yes for more than two non-collinear points. For collinear points the median is the middle point (or any point between the two central points if there is an even count). The Weiszfeld iteration converges to the unique minimiser for typical inputs.
What if the algorithm doesn't converge?
By default the function returns the best approximation reached within max_iter iterations. Pass fail_if_not_converged = true to throw an error instead. In practice the default of 10,000 iterations is more than enough for well-conditioned data; raise tolerance if you see slow convergence.
Does it work on non-point inputs?
ST_GeometricMedian expects a MultiPoint (or a Point, which returns itself). For other geometry types, extract vertices first with ST_DumpPoints and aggregate to a MultiPoint, or use ST_Centroid / ST_PointOnSurface instead.