2

Can someone please provide me an example of how to convert GeoJSON to shapefile using GeoTools?

3

I have followed the resource pointed out by @iant and.. Here's the solution:

public static void toShp(File geojson) throws IOException {     
    File shpFile = new File("test.shp");
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

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

    ShapefileDataStore shpDataStore = (ShapefileDataStore)  dataStoreFactory.createNewDataStore(params);


    InputStream in = new FileInputStream(geojson);
    int decimals = 15; 
    GeometryJSON gjson = new GeometryJSON(decimals); 
    FeatureJSON fjson = new FeatureJSON(gjson);

    FeatureCollection fc = fjson.readFeatureCollection(in);

    SimpleFeatureType type = (SimpleFeatureType) fc.getSchema();        
    shpDataStore.createSchema(type);

    Transaction transaction = new DefaultTransaction("create");

    String typeName = shpDataStore.getTypeNames()[0];

    SimpleFeatureSource featureSource = shpDataStore.getFeatureSource(typeName);

    if (featureSource instanceof FeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

        featureStore.setTransaction(transaction);
        try {

            featureStore.addFeatures(fc);

            transaction.commit();

        } catch (Exception ex) {
            ex.printStackTrace();
            transaction.rollback();

        } finally {
            transaction.close();
        }
    } else {
        System.out.println(typeName + " does not support read/write access");
    }


  }
1

I don't think there is a precanned example of this but you should be able to work out the basics from the cvs to shapefile example here. There is an unsupported GeoJSON module that should also be of help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.