I am trying to clean up some geo-spatial data that I have in a PostGIS database. Due to some imprecisions during the geocoding process, some points that must fall within the boundaries of a certain area, are being mapped to be very close, but outside the delimiting polygon of said area.
My first approach was to use the ST_ClosestPoint function in PostGIS, but with no success. The problem is, this function returns the closest point ON geometry A to geometry B (https://postgis.net/docs/ST_ClosestPoint.html). However, ON does not mean IN, since if I run the following query, that asks if the closest point ON A (a polygon) to B (a point) is contained in A:
SELECT ST_Contains(
ST_GeomFromText('POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'),
ST_ClosestPoint(
ST_GeomFromText('POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
)
) As ptwkt;
It returns false, meaning that the closest point is not contained in A at at all. What I want is the point within a polygon (contained in that Polygon) that is closest to another point. I want this, because the rest of my code checks if the points are within their respective areas. If this could be solved with a PostGIS query, it would be perfect.
The solution I found is to "shrink" the initial polygon by using ST_Buffer with a negative radius, and then obtain the closest point between my initial point the shrunken polygon. The closest point to the shrunken polygon falls within the initial polygon.
SELECT ST_Contains(
ST_GeomFromText('POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'),
ST_ClosestPoint(
ST_Buffer(ST_GeomFromText('POLYGON((175 150, 20 40, 50 60, 125 100, 175 150))'), -5),
ST_Buffer(ST_GeomFromText('POINT(110 170)'), 20)
)
) As ptwkt;
Now it returns true.