Search code examples
geotools

This is a point in a polygon. Latitude and Longitude Coordinates. GeoTools


Given a polygon that I trace with Coordinates of Latitude and Longitude, given an fline that I also receive in (in Latitude, Longitude).

I need to know if this point is inside my polygon or not

import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.PrecisionModel;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.operation.TransformException;

    private void isPointInPolygon() {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] coords = new Coordinate[] { new Coordinate(40.174256, -3.483185),
                new Coordinate(40.173279, -3.481339), new Coordinate(40.172597, -3.482541),
                new Coordinate(40.173403, -3.485401), new Coordinate(40.174256, -3.483185) };

        Polygon polygon = geometryFactory.createPolygon(coords);

        System.out.println("polygon : " + polygon.isValid());

        double scale = Math.pow(10, 2);
        PrecisionModel pm = new PrecisionModel(scale);
        GeometryFactory gf = new GeometryFactory(pm);

        Geometry testPoint = gf.createPoint(new Coordinate(40.173597, -3.483798));
        System.out.println("polygon contains point : " + polygon.contains(testPoint));
    }

// MAVEN

    <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>24-SNAPSHOT</version>
        </dependency>

The following code is correct, that is, it does not give any error.

I have doubt if its result is correct, or if I have to do some kind of conversion for the result to be correct. If I have to flatten it or if it is code, it already knows how to cure well.


Solution

  • Provided that your polygon is reasonably small it will be fine.

    If your polygon:

    • is approaching half of the world then the answer may be wrong.
    • crosses the anti-meridian (180W/E) then the answer will probably be wrong.
    • if the sides of the polygon are very long but have few points on them, then the answer may well be wrong.