Calculate if an object is inside a set of coordinates?

前端 未结 2 433
孤独总比滥情好
孤独总比滥情好 2021-02-04 01:03

I have a set of X and Y points that builds a shape and I need to know if an object is inside it or not what is the calculation to it ?

X and Y coords example:

         


        
2条回答
  •  旧时难觅i
    2021-02-04 01:50

    You may start from this: http://en.wikipedia.org/wiki/Point_in_polygon

    You also might look into JTS Topology Suite. And in particular use this function.

    EDIT: Here is example using JTS:

    import java.util.ArrayList;
    
    import com.vividsolutions.jts.geom.Coordinate;
    import com.vividsolutions.jts.geom.GeometryFactory;
    import com.vividsolutions.jts.geom.LinearRing;
    import com.vividsolutions.jts.geom.Point;
    import com.vividsolutions.jts.geom.Polygon;
    import com.vividsolutions.jts.geom.impl.CoordinateArraySequence;
    
    public class GeoTest {
    
      public static void main(final String[] args) {
    
        final GeometryFactory gf = new GeometryFactory();
    
        final ArrayList points = new ArrayList();
        points.add(new Coordinate(-10, -10));
        points.add(new Coordinate(-10, 10));
        points.add(new Coordinate(10, 10));
        points.add(new Coordinate(10, -10));
        points.add(new Coordinate(-10, -10));
        final Polygon polygon = gf.createPolygon(new LinearRing(new CoordinateArraySequence(points
            .toArray(new Coordinate[points.size()])), gf), null);
    
        final Coordinate coord = new Coordinate(0, 0);
        final Point point = gf.createPoint(coord);
    
        System.out.println(point.within(polygon));
    
      }
    
    }
    

    Here is example using AWT (which is simpler and is part of Java SE):

    import java.awt.Polygon;
    
    public class JavaTest {
    
      public static void main(final String[] args) {
    
        final Polygon polygon = new Polygon();
        polygon.addPoint(-10, -10);
        polygon.addPoint(-10, 10);
        polygon.addPoint(10, 10);
        polygon.addPoint(10, -10);
    
        System.out.println(polygon.contains(0, 0));
    
      }
    
    }
    

提交回复
热议问题