Search code examples
javacoordinatespath-2d

Detecting Coordinates Using Path 2d


I am trying to use the contains method provided to do a detection of the coordinates. As researched, the codes I use seem to work fine for others. But in this case, I am unable to get a positive return from my boolean despite it being within the drawn Path2D polygon.

PolygonCreation : For loop to draw coordinates contains to detect the coordinates

Path2D prettyPoly =new Path2D.Double();
                //Shape drawn
                // for loop to retrieve x,y coordinates for each location 
                for (int i = 0; i < coord1.length; i++) {
                    // split to retrieve x and y 
                    String[] splitCoord = coord1[i].split(" ");
                    // 0 - long 1 - lat
                     y1 = Double.parseDouble(splitCoord[0]);
                     x1 = Double.parseDouble(splitCoord[1]);
                     // to plot the starting point
                     if(i == 0){
                     System.out.println("Move to x"+x1 + "y" +y1);
                         prettyPoly.moveTo(x1, y1);



                     }else{

                    //   continue from starting point
                    System.out.println("Line to x  "+x1 + "y  " +y1);
                         prettyPoly.lineTo(x1, y1);

                     }

                }

                 prettyPoly.closePath();

                // check if contain
                Boolean h = prettyPoly.contains(1.38201544874088, 103.95321635529909);
                if(h == true){
                    System.out.println("true"); 
                }else{
                    System.out.println("false");
                }

given this set of codes, my coordinates are the same as the starting coordinate of the first location and have been detected false.

Link to path 2d documentation :

https://docs.oracle.com/javase/7/docs/api/java/awt/geom/Path2D.html

https://docs.oracle.com/javase/7/docs/api/java/awt/geom/Path2D.Double.html


Solution

  • You can try to do the following, instead of

    Boolean h = prettyPoly.contains(1.38201544874088, 103.95321635529909);
    

    try to use

    boolean h = prettyPoly.getBounds().contains(1.38201544874088, 103.95321635529909);
    

    In my simple test with Path2D this worked as expected.