Search code examples
javapolygonshapefilegeotools

How to correctly create a Polygon into a shapefile with Java?


I am trying to create shape files from a list of coordinates and it looks like it works but when I'm trying to view the shapefile in a shapefile viewer, it looks like there's no coordinates in my shape. Also if I then download my shapefile as geoJSON it looks empty like this: {"type":"GeometryCollection", "geometries": []}

So I have this one Java class, where I first create some dummy data, then create a Polygon SimpleFeatureType and then convert my list of points into a polygon and eventually try to write that polygon into a shapefile. I dont get any errors and all looks like running smoothly until I try to view it in the browser.

Here's my class with some debug prints :

import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;

public class Main {

    private static SimpleFeature toFeature(List<PolygonPoint> locations, SimpleFeatureType POLYGON,
            GeometryFactory geometryFactory) {

        Coordinate[] coords = new Coordinate[locations.size()];

        int i = 0;
        for (PolygonPoint location : locations) {
            Coordinate coord = new Coordinate(location.x, location.y, 0);
            coords[i] = (coord);
            i++;
        }

        Polygon polygon = geometryFactory.createPolygon(coords);

        System.out.println(polygon.toString());
        /**
         * Degub print in this point looks like this: POLYGON ((60.15396170672204
         * 24.665516804291176, 60.1548304906673 24.67437097771886, 60.156868902093464
         * 24.684907435753292, 60.16053593400762 24.681227944085034, 60.16351621152651
         * 24.677017850437107, 60.1641222365678 24.670587380672547, 60.163303711361145
         * 24.664257803508647, 60.16193970279525 24.6590194867117, 60.158682674758644
         * 24.65963863846621, 60.15396170672204 24.665516804291176)) So looks okay so
         * far...
         */
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(POLYGON);
        featureBuilder.add(polygon);
        return featureBuilder.buildFeature(null);
    }

    static class PolygonPoint {
        public double x;
        public double y;

        public PolygonPoint(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }

    private static void initData(List<PolygonPoint> locations) {
        locations.add(new PolygonPoint(60.1539617067220433, 24.6655168042911761));
        locations.add(new PolygonPoint(60.1548304906673010, 24.6743709777188585));
        locations.add(new PolygonPoint(60.1568689020934642, 24.6849074357532920));
        locations.add(new PolygonPoint(60.1605359340076191, 24.6812279440850340));
        locations.add(new PolygonPoint(60.1635162115265132, 24.6770178504371067));
        locations.add(new PolygonPoint(60.1641222365677990, 24.6705873806725471));
        locations.add(new PolygonPoint(60.1633037113611451, 24.6642578035086473));
        locations.add(new PolygonPoint(60.1619397027952516, 24.6590194867116992));
        locations.add(new PolygonPoint(60.1586826747586443, 24.6596386384662090));
        locations.add(new PolygonPoint(60.1539617067220433, 24.6655168042911761));
    }

    public static void main(String[] args) throws IOException, SchemaException {

        List<PolygonPoint> locations = new ArrayList<>();
        initData(locations);

        // create simple feature builder for the locations
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("polygonFeature");
        builder.setCRS(DefaultGeographicCRS.WGS84);
        builder.add(Polygon.TYPENAME_POLYGON, Polygon.class);
        SimpleFeatureType POLYGON = builder.buildFeatureType();

        DefaultFeatureCollection collection = new DefaultFeatureCollection();
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

        SimpleFeature feature = toFeature(locations, POLYGON, geometryFactory);
        collection.add(feature);
        collection.forEach(name -> System.out.println(name));
        /**
         * Degub print in this point looks like this:
         * SimpleFeatureImpl:polygonFeature=[SimpleFeatureImpl.Attribute:
         * Polygon<Polygon id=fid-77f7c041_174f9627c85_-8000>=POLYGON
         * ((60.15396170672204 24.665516804291176, 60.1548304906673 24.67437097771886,
         * 60.156868902093464 24.684907435753292, 60.16053593400762 24.681227944085034,
         * 60.16351621152651 24.677017850437107, 60.1641222365678 24.670587380672547,
         * 60.163303711361145 24.664257803508647, 60.16193970279525 24.6590194867117,
         * 60.158682674758644 24.65963863846621, 60.15396170672204 24.665516804291176))]
         * So looks okay still...
         */

        File shapeFile = new File(new File("2020-").getAbsolutePath() + "shapefile.shp");

        Map<String, Serializable> params = new HashMap<>();
        params.put("url", shapeFile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);

        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

        ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
        dataStore.createSchema(POLYGON);

        Transaction transaction = new DefaultTransaction("create");

        String typeName = dataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);

        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
            featureStore.setTransaction(transaction);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();

            } catch (Exception problem) {
                transaction.rollback();
            } finally {
                transaction.close();
            }
        }
    }
}

Then the 5 files get created as intended. However the shape is not correct and dont show anything. I was testing them with this tool: https://mapshaper.org/ but one can just google some shapefile online viewer.


Solution

  • Thanks to Ian Turton for linking the answer, the problem was solved by replacing this :

    builder.add(Polygon.TYPENAME_POLYGON, Polygon.class);

    with this:

    builder.add("the_geom", Polygon.class);