How to calculate the distance in meters between a geographic point and a given polygon?

Marcos Roriz Junior picture Marcos Roriz Junior · Jul 15, 2016 · Viewed 8.6k times · Source

First of all, I'm new to GIS, so pardon any mistakes. I need to discover the distance between a latitude and longitude point and a latitude/longitude polygon (regular or not). Precisely, I need to discover the minimal distance from a given point to a point in the polygon's boundary, as illustrated below. In the example, the closer distance from point p to the polygon is d. Note: I don't need the point, just the minimum distance.

Problem Illustration

After some reading, I've come up with the following minimum working example using the GeoTools API. However, I think I'm messing up in the output. Can anyone enlight me on how to get the minimum distance between a point and polygon in mteres?

MWE.java:

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;

public class MWE {

    public static void main(String[] args) throws Exception {
        GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] c = new Coordinate[5];
        c[0] = new Coordinate(-49.242986, -16.662430);
        c[1] = new Coordinate(-49.241999, -16.664465);
        c[2] = new Coordinate(-49.239146, -16.663828);
        c[3] = new Coordinate(-49.239832, -16.661443);
        c[4] = new Coordinate(-49.242986, -16.662430);

        Geometry geo = gf.createPolygon(c);

        Point p = gf.createPoint(new Coordinate(-49.246870, -16.665493));

        double distance = geo.distance(p);

        System.out.println("Distance: " + distance);

    }
}

Answer

aengus picture aengus · Jul 15, 2016

So what you are doing is correct, but it will return distance in geodetic units (degrees of arc) rather than metres. You have two options:

  1. transform the point and the polygon geometries to a planar reference system http://docs.geotools.org/latest/tutorials/geometry/geometrycrs.html
  2. Use the GeodeticCalculator http://docs.geotools.org/stable/userguide/library/referencing/calculator.html

To use the GeodeticCalculator you will need to determine the closest point on the polygon boundary to your point. e.g. DistanceOp.closestPoints(geo, p)[0]

// adapted from http://docs.geotools.org/stable/userguide/library/referencing/calculator.html
CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
GeodeticCalculator gc = new GeodeticCalculator(crs);
gc.setStartingPosition( JTS.toDirectPosition(  DistanceOp.closestPoints(geo, p)[0], crs ) );
gc.setDestinationPosition( JTS.toDirectPosition( p, crs ) );

double distance = gc.getOrthodromicDistance();