Search code examples
javajavafxshapefilegeotools

How I can get all the points of a polygon in a shapeFile .shp using GeoTools?


This is my first question in stackoverflow so I hope that I am doing it in the right way.

I am using geotools to read a shapeFile (.shp) and I cannot find the function to get all the points of the polygon. By now I have the following code:

public class ImportShapeFileService implements ImportShapeFileServiceInterface {

    @Override
    public void loadShapeFile(File shapeFile) throws MdfException {

        FileDataStore store;
        try {
            store = FileDataStoreFinder.getDataStore(shapeFile);
            SimpleFeatureSource featureSource = store.getFeatureSource();
            SimpleFeatureCollection collection = featureSource.getFeatures();

            ReferencedEnvelope env = collection.getBounds();
            double left = env.getMinX();
            double right = env.getMaxX();
            double top = env.getMaxY();
            double bottom = env.getMinY();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I am getting the four bounds of the shapFile, but not the points of the polygon that contains, is it possible to do that?

Thank you.


Solution

  • Depending on what you want to do with the points, I'd do something like:

    try(SimpleFeatureIterator itr1 = features.features()){
      while(itr1.hasNext()){
         SimpleFeature f = itr1.next();
         Geometry g = (Geometry)f.getDefaultGeometry();
         Coordinate[] coords = g.getCoordinates();
         // do something with the coordinates
       }
    }
    

    If you must have Point rather than just the coordinates (and you are sure you have polygons then you could use:

      Geometry g = (Geometry)f.getDefaultGeometry();
      for(int i=0;i<g.getNumPoints();i++) {
        Point p=((Polygon)g).getExteriorRing().getPointN(i);
      }