[GIS] GeoTools JTS: Snap a Point to a polygon (equivalent to PostGis ST_ClosestPoint)

geotoolsjts-topology-suitesnapping

I'm using GeoTools JTS libraries in Java and I want to find the nearest point inside polygon shape to some single target location. This is exactly what in PostGis ST_ClosestPoint does.

I found this article discussing "Snap a Point to a Line".

So trivial solution will be:

-Dump polygon to lines
-Snap a Point for each above Line
-Calculate the distance between the point and "the snapped" point
-Take the one with minimum distance

How can I achieve my requirement in GeoTools in more "elegant" way?

EDIT:

Actually I'm not sure if the link to snap a point doing exactly what ST_Closest because I don't understand how it's actually extracting the closest point…

Best Answer

JTS's DistanceOP#nearestPoints might be an easy way. I have not tested it.

http://tsusiatsoftware.net/jts/javadoc/com/vividsolutions/jts/operation/distance/DistanceOp.html#nearestPoints%28com.vividsolutions.jts.geom.Geometry,%20com.vividsolutions.jts.geom.Geometry%29

Compute the the nearest points of two geometries. The points are presented in the same order as the input Geometries.

Related Question